fork download
  1. #include <chrono>
  2. #include <iostream>
  3. #include <random>
  4. #include <algorithm>
  5. #include <iterator>
  6. #include <functional>
  7.  
  8. using namespace std;
  9.  
  10. int main()
  11. {
  12. //Generate a vector of random integers from 1 to 100
  13. random_device rnd_device;
  14. mt19937 rnd_engine(rnd_device());
  15. uniform_int_distribution<int> rnd_dist(1, 100);
  16. auto gen = std::bind(rnd_dist, rnd_engine);
  17. vector<int> rand_vec(5000);
  18. generate(begin(rand_vec), end(rand_vec), gen);
  19. volatile int nLow, nMid, nHigh;
  20.  
  21. //Count the number of values in each of three different ranges
  22. //Run the test a few times
  23. for (int n = 0; n != 10; ++n) {
  24. {
  25. //Sort the conditional statements in order of likelyhood
  26. nLow = nMid = nHigh = 0;
  27. auto start = chrono::high_resolution_clock::now();
  28. for (int& i : rand_vec) {
  29. if (i >= 20 && i < 95) ++nMid; //Most likely branch
  30. else if (i < 20) ++nLow;
  31. else if (i >= 95) ++nHigh; //Least likely branch
  32. }
  33. auto end = chrono::high_resolution_clock::now();
  34. cout << "Sorted:\t\t\t" << chrono::duration_cast<chrono::nanoseconds>(end-start).count() << "ns" << endl;
  35. }
  36.  
  37. //Run the test again, but now sort the conditional statements in reverse-order of likelyhood
  38. {
  39. nLow = nMid = nHigh = 0;
  40. auto start = chrono::high_resolution_clock::now();
  41. for (int& i : rand_vec) {
  42. if (i >= 95) ++nHigh; //Least likely branch
  43. else if (i < 20) ++nLow;
  44. else if (i >= 20 && i < 95) ++nMid; //Most likely branch
  45. }
  46. auto end = chrono::high_resolution_clock::now();
  47. cout << "Reverse-sorted: \t" << chrono::duration_cast<chrono::nanoseconds>(end-start).count() << "ns" << endl;
  48. }
  49.  
  50.  
  51. cout << endl;
  52. }
  53. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Sorted:			15839ns
Reverse-sorted: 	14896ns

Sorted:			15049ns
Reverse-sorted: 	14245ns

Sorted:			13613ns
Reverse-sorted: 	13869ns

Sorted:			12819ns
Reverse-sorted: 	13196ns

Sorted:			12137ns
Reverse-sorted: 	12499ns

Sorted:			11439ns
Reverse-sorted: 	12255ns

Sorted:			11401ns
Reverse-sorted: 	12738ns

Sorted:			10848ns
Reverse-sorted: 	12667ns

Sorted:			10663ns
Reverse-sorted: 	12363ns

Sorted:			10403ns
Reverse-sorted: 	12083ns