Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // g++ -O2 -W -Wall -Wextra printf-vs-cout.cpp -o printf-vs-cout.exe && ./printf-vs-cout.exe 1>/dev/null
- #include <iostream>
- #include <stdio.h>
- #include <unistd.h>// Write
- #ifdef WIN32
- # include <windows.h>
- #else
- # include <sys/time.h>
- # include <sys/resource.h>
- #endif
- using namespace std;
- double get_time();
- /*
- Printf no args
- 4.88426
- Printf 1 arg
- 18.5892
- Puts no args
- 4.51563
- Fputs no args
- 2.98327
- Write no args
- 20.6939
- Cout no args
- 5.32271
- Cout 1 arg
- 27.0982
- */
- enum { LOOP_SIZE = 100000000 };
- #define makeLoop( name, ... ) \
- cerr << name"\n"; \
- begin = get_time(); \
- for( int i=0; i<LOOP_SIZE; ++i ) \
- { \
- __VA_ARGS__; \
- } \
- cerr << '\t' << get_time()-begin << '\n';
- int main()
- {
- double begin = 0;
- makeLoop("Printf no args", printf("test\n"));
- makeLoop("Printf 1 arg", printf("test %d\n", i));
- cerr << '\n';
- makeLoop("Puts no args", puts("test\n"));
- makeLoop("Fputs no args", fputs("test\n", stdout));
- cerr << '\n';
- makeLoop("Write no args", write(1, "test\n", 5));
- cerr << '\n';
- makeLoop("Cout no args", cout << "test\n");
- makeLoop("Cout 1 arg", cout << "test" << i << '\n');
- return 0;
- }
- double get_time()
- {
- # ifdef WIN32
- LARGE_INTEGER t, f;
- QueryPerformanceCounter(&t);
- QueryPerformanceFrequency(&f);
- return (double)t.QuadPart/(double)f.QuadPart;
- # else
- struct timeval t;
- struct timezone tzp;
- gettimeofday(&t, &tzp);
- return t.tv_sec + t.tv_usec*1e-6;
- # endif
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement