Benchmark Sections
- Test Data Generation
- Custom Fast Input
- Standard
scanf()
- Default
cin
- Optimized
cin
- Results Summary
Test Data Generator
#include <cstdio>
#include <cstdlib>
#include <windows.h>
#define reg register
using namespace std;
const int TOTAL_ENTRIES = 1919810;
int main() {
freopen("test_input.txt", "w", stdout);
srand(GetTickCount());
for (reg int i = 0; i < TOTAL_ENTRIES; ++i) {
printf("%d ", rand() - 16384);
}
return 0;
}
Custom Fast Integer Input
// Elapsed time for 1919810 integers: ~210ms
#include <cstdio>
#include <windows.h>
#define reg register
using namespace std;
const int TOTAL_ENTRIES = 1919810;
inline int fastIntRead() {
reg int val = 0;
reg int sign = 1;
reg char c;
while ((c = getchar()) && (c < '0' || c > '9')) {
if (c == '-') sign = -1;
}
do {
val = (val << 3) + (val << 1) + (c ^ 48);
} while ((c = getchar()) && c >= '0' && c <= '9');
return val * sign;
}
int main() {
freopen("test_input.txt", "r", stdin);
long start = GetTickCount();
for (int i = 0; i < TOTAL_ENTRIES; ++i) {
fastIntRead();
}
long end = GetTickCount();
printf("%ld", end - start);
return 0;
}
Standard scanf()
// Elapsed time for 1919810 integers: ~670ms
#include <cstdio>
#include <windows.h>
using namespace std;
const int TOTAL_ENTRIES = 1919810;
int main() {
freopen("test_input.txt", "r", stdin);
int tmp;
long start = GetTickCount();
for (int i = 0; i < TOTAL_ENTRIES; ++i) {
scanf("%d", &tmp);
}
long end = GetTickCount();
printf("%ld", end - start);
return 0;
}
Default Unoptimized cin
// Elapsed time for 1919810 integers: ~1.3s (1300ms)
#include <iostream>
#include <cstdio>
#include <windows.h>
using namespace std;
const int TOTAL_ENTRIES = 1919810;
int main() {
freopen("test_input.txt", "r", stdin);
int tmp;
long start = GetTickCount();
for (int i = 0; i < TOTAL_ENTRIES; ++i) {
cin >> tmp;
}
long end = GetTickCount();
cout << (end - start) << endl;
return 0;
}
cin with Synchronization Disabled
// Elapsed time for 1919810 integers: ~250ms
#include <iostream>
#include <cstdio>
#include <windows.h>
using namespace std;
const int TOTAL_ENTRIES = 1919810;
int main() {
freopen("test_input.txt", "r", stdin);
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tmp;
long start = GetTickCount();
for (int i = 0; i < TOTAL_ENTRIES; ++i) {
cin >> tmp;
}
long end = GetTickCount();
cout << (end - start) << endl;
return 0;
}
Results Summary
- Custom fast input is slightly faster than optimized
cin
- If you do not want to implement a custom fast read function, using
cin with disabled synchronization offers excellent performence that is sufficeint for most competitiev programming use cases.