fork download
  1. #include <array>
  2. #include <cstdint>
  3. #include <cstring>
  4. #include <iomanip>
  5. #include <iostream>
  6. #include <sys/time.h>
  7.  
  8.  
  9. double GetCurrentTimeSeconds()
  10. {
  11. timeval tv;
  12. gettimeofday(&tv, NULL);
  13. return double (tv.tv_sec) + 0.000001 * tv.tv_usec;
  14. }
  15.  
  16.  
  17. struct Key
  18. {
  19. std::array<uint8_t, 6> MACAddress;
  20. uint16_t EtherType;
  21. };
  22.  
  23.  
  24. uint64_t GetKeyValue(Key slowkey)
  25. {
  26. uint64_t key;
  27. std::memcpy(&key, &slowkey, sizeof(key));
  28. return key;
  29. }
  30.  
  31.  
  32. union FastKey
  33. {
  34. Key key;
  35. char data[sizeof(Key)];
  36. };
  37.  
  38.  
  39. inline uint64_t GetKeyValue(FastKey fastKey)
  40. {
  41. uint64_t key = 0;
  42. key |= uint64_t(fastKey.data[0]) << 56;
  43. key |= uint64_t(fastKey.data[1]) << 48;
  44. key |= uint64_t(fastKey.data[2]) << 40;
  45. key |= uint64_t(fastKey.data[3]) << 32;
  46. key |= uint64_t(fastKey.data[4]) << 24;
  47. key |= uint64_t(fastKey.data[5]) << 16;
  48. key |= uint64_t(fastKey.data[6]) << 8;
  49. key |= uint64_t(fastKey.data[7]) << 0;
  50. return key;
  51. }
  52.  
  53.  
  54. template<typename KeyType>
  55. double Test(KeyType inKeyType, uint64_t & preventOptimization)
  56. {
  57. double start = GetCurrentTimeSeconds();
  58. for (uint64_t i = 0; i < 1000000; ++i)
  59. {
  60. preventOptimization += GetKeyValue(inKeyType);
  61. }
  62. return GetCurrentTimeSeconds() - start;
  63. }
  64.  
  65.  
  66. Key GetRandomKey()
  67. {
  68. // not really random, but sufficient to prevent
  69. // optimizations from spoiling the benchmark.
  70.  
  71. Key key;
  72. key.MACAddress[0] = static_cast<uint8_t>(time(0) % 256);
  73. return key;
  74. }
  75.  
  76.  
  77. int main()
  78. {
  79. std::cout.setf(std::ios::fixed);
  80.  
  81. uint64_t preventOptimization = 0;
  82.  
  83. Key slowKey = GetRandomKey();
  84. std::cout << "Using slow key: " << Test(slowKey, preventOptimization) << " seconds." << std::endl;
  85. std::cout << preventOptimization << std::endl;
  86.  
  87. FastKey fastKey;
  88. fastKey.key = slowKey;
  89. std::cout << "Using fast key: " << Test(fastKey, preventOptimization) << " seconds." << std::endl;
  90. std::cout << preventOptimization << std::endl;
  91. }
Success #stdin #stdout 0s 2884KB
stdin
Standard input is empty
stdout
Using slow key: 0.002371 seconds.
12524011040378938496
Using fast key: 0.000001 seconds.
12524003766914938496