File size: 1,903 Bytes
1fd0050 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | // Benchmark testlib readInt speed
#include <bits/stdc++.h>
#include <chrono>
using namespace std;
// Simulate ouf.readInt() with the same testlib approach
// testlib reads from stdin character by character
int main() {
// Generate 10M integers to a file, then time reading them
int N = 10000000;
// Generate
{
FILE* f = fopen("/tmp/bench_input.txt", "w");
mt19937 rng(42);
for (int i = 0; i < N; i++) {
if (i) fprintf(f, " ");
fprintf(f, "%d", (int)(rng() % 100000) + 1);
}
fprintf(f, "\n");
fclose(f);
}
// Read using getchar (similar to testlib)
{
FILE* f = fopen("/tmp/bench_input.txt", "r");
auto start = chrono::steady_clock::now();
long long sum = 0;
for (int i = 0; i < N; i++) {
int c = fgetc(f);
while (c < '0' || c > '9') { c = fgetc(f); if (c == EOF) break; }
int x = 0;
while (c >= '0' && c <= '9') { x = x*10+(c-'0'); c = fgetc(f); }
sum += x;
}
auto end = chrono::steady_clock::now();
double elapsed = chrono::duration<double>(end - start).count();
printf("fgetc: Read %d ints in %.3fs (%.1f M/s), sum=%lld\n", N, elapsed, N/elapsed/1e6, sum);
fclose(f);
}
// Read using scanf (testlib uses InStream which is similar)
{
FILE* f = fopen("/tmp/bench_input.txt", "r");
auto start = chrono::steady_clock::now();
long long sum = 0;
for (int i = 0; i < N; i++) {
int x;
fscanf(f, "%d", &x);
sum += x;
}
auto end = chrono::steady_clock::now();
double elapsed = chrono::duration<double>(end - start).count();
printf("fscanf: Read %d ints in %.3fs (%.1f M/s), sum=%lld\n", N, elapsed, N/elapsed/1e6, sum);
fclose(f);
}
return 0;
}
|