fork download
  1. #include <cstdlib>
  2. #include <cstdio>
  3. #include <cstring>
  4. #include <ctime>
  5. #include <iostream>
  6. #include <vector>
  7. #include <sys/time.h>
  8.  
  9. double get_current_time()
  10. {
  11. timeval tv;
  12. gettimeofday(&tv, NULL);
  13. return double (tv.tv_sec) + 0.000001 * tv.tv_usec;
  14. }
  15.  
  16. int get_int_v1(const char * data) { return *reinterpret_cast<const int*>(data); }
  17. int get_int_v2(const char * data) { int result; memcpy(&result, data, sizeof(result)); return result; }
  18.  
  19. const unsigned iterations = 200 * 1000 * 1000;
  20.  
  21. double test_v1(const char * c, unsigned & prevent_optimization)
  22. {
  23. double start = get_current_time();
  24. for (unsigned i = 0; i != iterations; ++i)
  25. {
  26. prevent_optimization += get_int_v1(c);
  27. }
  28. return get_current_time() - start;
  29. }
  30.  
  31. double test_v2(const char * c, unsigned & prevent_optimization)
  32. {
  33. double start = get_current_time();
  34. for (unsigned i = 0; i != iterations; ++i)
  35. {
  36. prevent_optimization += get_int_v2(c);
  37. }
  38. return get_current_time() - start;
  39. }
  40.  
  41. int main()
  42. {
  43. srand(time(0));
  44.  
  45. // Initialize data
  46. std::vector<int> numbers(1000);
  47. for (std::vector<int>::size_type i = 0; i != numbers.size(); ++i)
  48. {
  49. numbers[i] = i;
  50. }
  51.  
  52. // Repeat benchmark 4 times.
  53. for (unsigned i = 0; i != 4; ++i)
  54. {
  55. unsigned p = 0;
  56. std::vector<int>::size_type index = rand() % numbers.size();
  57. const char * c = reinterpret_cast<const char *>(&numbers[index]);
  58. std::cout << "v1: " << test_v1(c, p) << std::endl;
  59. std::cout << "v2: " << test_v2(c, p) << std::endl << std::endl;
  60. }
  61. }
Success #stdin #stdout 1.94s 2856KB
stdin
Standard input is empty
stdout
v1: 0.176457
v2: 0.557588

v1: 0.17654
v2: 0.220581

v1: 0.176826
v2: 0.22012

v1: 0.176131
v2: 0.220633