-
-
Save jotaki/6804331 to your computer and use it in GitHub Desktop.
simple hash:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <time.h> | |
#include <fcntl.h> | |
#include <sys/stat.h> | |
#define PATH "numbers.txt" | |
#define CHUNK_SIZE 4096 | |
static inline unsigned int simple_hash(char ** s) | |
{ | |
register unsigned int h = 52543; | |
char * p = *s; | |
int c; | |
do { | |
c = *p++; | |
h = ((c & 0xf) ^ ((*p >> 4) & 0xf)) + (h << 1); | |
h += ((c & 0xf0) + *p) * 11; | |
h ^= (c * *p) << 19; | |
} while(*p != '\n'); | |
*s = p; | |
return h; | |
} | |
int main(int argc, char * argv[]) | |
{ | |
struct stat stats; | |
stat(PATH, &stats); | |
char *buf = malloc(stats.st_size + 1); | |
char *cur = buf; | |
char *end = buf + stats.st_size; | |
clock_t start, stop; | |
int c = 0; | |
start = clock(); | |
// Load file into memory | |
int fp = open(PATH, O_RDONLY); | |
if(fp == -1) | |
goto _return; | |
off_t in; | |
while ((in = read(fp, cur, CHUNK_SIZE))) { | |
cur += in; | |
} | |
cur[0] = '\n'; | |
// Do the hashing | |
cur = buf; | |
if(argc-1) { | |
while(cur < end) { | |
simple_hash(&cur); | |
++c; | |
} | |
} | |
else { | |
while(cur < buf + stats.st_size) { | |
printf("%u\n", simple_hash(&cur)); | |
++c; | |
} | |
} | |
close(fp); | |
stop = clock(); | |
printf("%d in %ld ms\n", c, | |
(long)(stop - start) * 1000 / CLOCKS_PER_SEC); | |
_return: | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment