/compute_checksum.cpp Secret
Last active
June 12, 2020 08:37
This file contains 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 <cstdio> | |
#include <algorithm> | |
#include <sys/time.h> | |
// Current time in seconds. | |
long double wallclock() { | |
timeval tim; | |
gettimeofday(&tim, NULL); | |
return tim.tv_sec + (tim.tv_usec / 1000000.0L); | |
} | |
// Compute checksum. | |
long compute_checksum(const char *filename) { | |
std::FILE * const f = std::fopen(filename, "r"); | |
std::fseek(f, 0, SEEK_END); | |
const long size = std::ftell(f); | |
std::rewind(f); | |
char *buf = new char[1 << 20]; | |
long ans = 0, left = size; | |
while (left > 0) { | |
long toread = std::min(1L << 20, left); | |
std::fread(buf, 1, toread, f); | |
for (long i = 0; i < toread; ++i) | |
ans += buf[i]; | |
left -= toread; | |
} | |
delete[] buf; | |
std::fclose(f); | |
return ans; | |
} | |
int main(int, char **argv) { | |
for (int i = 0; i < 3; ++i) { | |
long double start = wallclock(); | |
long sum = compute_checksum(argv[1]); | |
fprintf(stderr, "checksum = %ld, time = %.2Lfs\n", | |
sum, wallclock() - start); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment