Skip to content

Instantly share code, notes, and snippets.

@WojciechMula
Created February 15, 2017 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WojciechMula/6200d3991c366b7d6b53c2dd35b785dc to your computer and use it in GitHub Desktop.
Save WojciechMula/6200d3991c366b7d6b53c2dd35b785dc to your computer and use it in GitHub Desktop.
How fast can you count lines?
// another method for
// https://github.com/lemire/Code-used-on-Daniel-Lemire-s-blog/blob/master/2017/02/14/newlines.c
#define haszero(v) (((v) - 0x0101010101010101llu) & ~(v) & 0x8080808080808080llu) // magick provided by https://graphics.stanford.edu/~seander/bithacks.html
size_t swarcount(char * buffer, size_t size) {
size_t cnt = 0;
const uint64_t nls = 0x0a0a0a0a0a0a0a0allu;
size_t i=0;
while (i + 8 < size) {
const uint64_t v = *(uint64_t*)(buffer + i);
if (haszero(v ^ nls)) {
for (size_t j=0; j < 8; j++) {
if (buffer[i + j] == '\n') cnt ++;
}
}
i += 8;
}
for(/**/; i < size; i++)
if(buffer[i] == '\n') cnt ++;
return cnt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment