SHARE
TWEET

BenchMark - printf vs cout vs write vs puts vs fputs

a guest Mar 25th, 2014 138 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // g++ -O2 -W -Wall -Wextra printf-vs-cout.cpp -o printf-vs-cout.exe && ./printf-vs-cout.exe 1>/dev/null
  2. #include <iostream>
  3. #include <stdio.h>
  4. #include <unistd.h>// Write
  5. #ifdef WIN32
  6. #       include <windows.h>
  7. #else
  8. #       include <sys/time.h>
  9. #       include <sys/resource.h>
  10. #endif
  11. using namespace std;
  12.  
  13. double get_time();
  14.  
  15.  
  16. /*
  17.         Printf no args
  18.                 4.88426
  19.         Printf 1 arg
  20.                 18.5892
  21.  
  22.         Puts no args
  23.                 4.51563
  24.         Fputs no args
  25.                 2.98327
  26.  
  27.         Write no args
  28.                 20.6939
  29.  
  30.         Cout no args
  31.                 5.32271
  32.         Cout 1 arg
  33.                 27.0982
  34. */
  35.  
  36. enum { LOOP_SIZE = 100000000 };
  37.  
  38. #define makeLoop( name, ... ) \
  39.         cerr << name"\n"; \
  40.         begin = get_time(); \
  41.         for( int i=0; i<LOOP_SIZE; ++i ) \
  42.         { \
  43.                 __VA_ARGS__; \
  44.         } \
  45.         cerr << '\t' << get_time()-begin << '\n';
  46.  
  47.  
  48. int main()
  49. {
  50.         double begin = 0;
  51.  
  52.         makeLoop("Printf no args", printf("test\n"));
  53.         makeLoop("Printf 1 arg", printf("test %d\n", i));
  54.         cerr << '\n';
  55.         makeLoop("Puts no args", puts("test\n"));
  56.         makeLoop("Fputs no args", fputs("test\n", stdout));
  57.         cerr << '\n';
  58.         makeLoop("Write no args", write(1, "test\n", 5));
  59.         cerr << '\n';
  60.         makeLoop("Cout no args", cout << "test\n");
  61.         makeLoop("Cout 1 arg", cout << "test" << i << '\n');
  62.  
  63.         return 0;
  64. }
  65.  
  66.  
  67. double get_time()
  68. {
  69. #       ifdef WIN32
  70.                 LARGE_INTEGER t, f;
  71.                 QueryPerformanceCounter(&t);
  72.                 QueryPerformanceFrequency(&f);
  73.                 return (double)t.QuadPart/(double)f.QuadPart;
  74. #       else
  75.                 struct timeval t;
  76.                 struct timezone tzp;
  77.                 gettimeofday(&t, &tzp);
  78.                 return t.tv_sec + t.tv_usec*1e-6;
  79. #       endif
  80. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top