We evaluated the performance of various C++ input methods by processing 1,000,000 randomly generated integers (within INT32 range) on an Intel Core i5-12400 system running Windows 11.
Tested Input Methods
- Standard scanf
- Standard cin
- Custom fast read
- Bitwise optimized fast read
- fread + bitwise optimized read
- cin with sync disabled
- cin with sync disabled and tie broken
Implementation Code
Data Generator
#include <cstdio>
#include <cstdlib>
#include <ctime>
const int SIZE = 1e6;
int generate_random() {
bool sign = rand() & 1;
long long value = rand() + (rand() << 15) + (rand() << 30);
return sign ? -(value % (1LL << 32)) : value % (1LL << 32);
}
int main() {
freopen("input.txt", "w", stdout);
srand(time(0));
for(int i = 0; i < SIZE; i++)
printf("%d ", generate_random());
return 0;
}
Performance Measurement
#include <windows.h>
void measure_performance(const char* method_name, function<void()> test_func) {
LARGE_INTEGER start, end, freq;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&start);
test_func();
QueryPerformanceCounter(&end);
printf("%s: %.4f ms\n", method_name,
1000.0 * (end.QuadPart - start.QuadPart) / freq.QuadPart);
}
Input Method Implementations
Standard scanf
int val;
for(int i = 0; i < SIZE; i++)
scanf("%d", &val);
Fast Read with Bit Optimization
inline int fast_read() {
int num = 0, sign = 1;
char c = getchar();
while(c < '0' || c > '9') {
if(c == '-') sign = -1;
c = getchar();
}
while(c >= '0' && c <= '9') {
num = (num << 3) + (num << 1) + (c ^ 48);
c = getchar();
}
return num * sign;
}
Buffered Read
const int BUFFER_SIZE = 1 << 20;
char buffer[BUFFER_SIZE];
char* buffer_ptr = buffer;
inline char get_char() {
if(buffer_ptr == buffer + BUFFER_SIZE) {
fread(buffer, 1, BUFFER_SIZE, stdin);
buffer_ptr = buffer;
}
return *buffer_ptr++;
}
int buffered_read() {
int num = 0, sign = 1;
char c = get_char();
while(!isdigit(c)) {
if(c == '-') sign = -1;
c = get_char();
}
while(isdigit(c)) {
num = (num << 3) + (num << 1) + (c ^ 48);
c = get_char();
}
return num * sign;
}
Performance Results
| Method | Average Time (ms) |
|---|---|
| scanf | 435.7 |
| cin | 1185.3 |
| Fast Read | 209.7 |
| Bitwise Read | 216.3 |
| Buffered Read | 41.5 |
| cin (no sync) | 130.3 |
| cin (no sync/tie) | 137.2 |
The buffered read implementation demonstrated the best performance, being approximately 10x faster than standard cin and 3x faster than optimized cin with disabled synchronization.