Skip to content

Instantly share code, notes, and snippets.

@Cyan4973
Created October 22, 2021 22:59
Show Gist options
  • Save Cyan4973/0d3de2efb87a83c88dadf1a3421dadb8 to your computer and use it in GitHub Desktop.
Save Cyan4973/0d3de2efb87a83c88dadf1a3421dadb8 to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE // O_DIRECT
#include <xxhash.h> // XXH64
#include <stddef.h> // size_t
#include <stdint.h> // uint64_t
typedef uint64_t u64;
void genRand(u64* a64, size_t a64Size)
{
u64 r = XXH64(NULL, 0, a64Size);
for (size_t n=0; n<a64Size; n++) {
a64[n] = r;
r = XXH64(&r, 8, 0);
}
}
#include <fcntl.h> // open
#include <stdlib.h> // malloc
#include <time.h> // clock_t
#include <stdio.h> // fopen, fclose,
#include <assert.h>
u64 getFileSize(FILE* f)
{
fseek(f, 0, SEEK_END); // seek to end of file
u64 const size = ftell(f); // get current file pointer
fseek(f, 0, SEEK_SET);
return size;
}
#define NB_RAND_ACC 10000
int main(int argc, const char* argv[])
{
assert(argc == 2);
const char* const filename = argv[1];
printf("opening %s ...\n", filename);
//int const lf = open(filename, O_RDONLY | O_DIRECT); assert(lf != -1);
//FILE* const f = fdopen(lf, "rb"); assert(f != NULL);
FILE* const f = fopen(filename, "rb"); assert(f != NULL);
u64 const filesize = getFileSize(f);
printf(" size = %llu \n", (unsigned long long)filesize);
u64* const r64 = malloc(NB_RAND_ACC * sizeof(*r64)); assert(r64 != NULL);
genRand(r64, NB_RAND_ACC);
u64 acc = 0;
clock_t const start = clock();
for (size_t n=0; n<NB_RAND_ACC; n++) {
u64 const pos = r64[n] % filesize;
//printf("pos = %9u \n", (unsigned)pos);
int const ir = fseek(f, pos, SEEK_SET);
assert(ir==0);
uint8_t val;
size_t const n = fread(&val, 1, 1, f);
assert(n==1);
acc += val;
}
clock_t const duration = clock() - start;
printf("%u reads => %.3f seconds (total=%llu) \n", NB_RAND_ACC, (double)duration / CLOCKS_PER_SEC, (unsigned long long)acc);
free(r64);
fclose(f);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment