public
Last active

cin / scanf comparison

  • Download Gist
Makefile
Makefile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
all: xor-c xor-cpp xor-cpp-noflush rand
 
test: xor-c xor-cpp xor-cpp-noflush
time ./xor-c < rand.txt
time ./xor-cpp < rand.txt
time ./xor-cpp-noflush < rand.txt
 
rand: rand.c
gcc -Wall rand.c -o rand
 
xor-c: xor.c
gcc -Wall -O4 xor.c -o xor-c
 
xor-cpp: xor.cc
g++ -Wall -O4 xor.cc -o xor-cpp
 
xor-cpp-noflush: xor-noflush.cc
g++ -Wall -O4 xor-noflush.cc -o xor-cpp-noflush
README
1 2 3 4 5 6 7 8 9 10 11 12 13
Comparison between cin and scanf
 
Usage:
 
make
 
./rand > rand.txt
Ctrl-C after a few seconds
 
wc rand.txt
 
time ./xor-c < rand.txt
time ./xor-cpp < rand.txt
rand.c
C
1 2 3 4 5 6 7 8 9 10 11
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
 
int main(int argc, char **argv) {
srand(time(NULL));
while (1)
printf("%d\n", rand());
}
xor-noflush.cc
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
 
int main(int argc, char **argv) {
int parity = 0;
int x;
 
std::ios::sync_with_stdio(false);
while (std::cin >> x)
parity ^= x;
std::cout << parity << std::endl;
 
return 0;
}
xor.c
C
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <stdio.h>
 
int main(int argc, char **argv) {
int parity = 0;
int x;
 
while (1 == scanf("%d", &x))
parity ^= x;
printf("%d\n", parity);
 
return 0;
}
xor.cc
C++
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
 
int main(int argc, char **argv) {
int parity = 0;
int x;
 
while (std::cin >> x)
parity ^= x;
std::cout << parity << std::endl;
 
return 0;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.