You use strings.
As explained here Hunting for the fastest implementation of Hamming Distance C if you can use char *, my experiments conclude that for Gcc 4.7.2 on Intel Xeon X5650 the fastest function of calculating the distance from hammming for small (char arrays):
// na = length of both strings unsigned int HammingDistance(const char* a, unsigned int na, const char* b) { unsigned int num_mismatches = 0; while (na) { if (*a != *b) ++num_mismatches; --na; ++a; ++b; } return num_mismatches; }
If your problem allows you to set the upper limit of the distance, so that you do not need large distances, and this limit is always less than the length of the lines, the above example can be further optimized for:
// na = length of both strings, dist must always be < na unsigned int HammingDistance(const char* const a, const unsigned int na, const char* const b, const unsigned int dist) { unsigned int i = 0, num_mismatches = 0; while(i <= dist) { if (a[i] != b[i]) ++num_mismatches; ++i; } while(num_mismatches <= dist && i < na) { if (a[i] != b[i]) ++num_mismatches; ++i; } return num_mismatches; }
I'm not sure that const does anything regarding speed, but I use it anyway ...
pdrak
source share