fork download
  1. #include <iostream>
  2. #include <ctime>
  3. #include <cstdint>
  4. using std::cout;
  5. using std::endl;
  6.  
  7. std::uint32_t rand_value;
  8.  
  9. std::uint32_t lcg()
  10. {
  11. const auto a = 22695477u;
  12. const auto c = 1u;
  13.  
  14. rand_value = a * rand_value + c;
  15. return rand_value;
  16. }
  17.  
  18. enum func_method {log_or, mult};
  19.  
  20. template <typename test_type, func_method method>
  21. void test_func()
  22. {
  23. const unsigned long end = 800'000'000;
  24. unsigned int sum = 0;
  25.  
  26. std::uint32_t mask = 32767;
  27.  
  28. auto clock_begin = std::clock();
  29. if (method == func_method::log_or)
  30. for (unsigned long i = 0; i < end; ++i)
  31. {
  32. test_type a = lcg() & mask;
  33. test_type b = lcg() & mask;
  34. if (a == 0 || b == 0)
  35. ++sum;
  36. }
  37. else if (method == func_method::mult)
  38. for (unsigned long i = 0; i < end; ++i)
  39. {
  40. test_type a = lcg() & mask;
  41. test_type b = lcg() & mask;
  42. if (a * b == 0)
  43. ++sum;
  44. }
  45. else
  46. cout << "Invalid method" << endl;
  47. auto clock_end = std::clock();
  48.  
  49. cout << "sum: " << sum << endl;
  50. cout << "time: " << double(clock_end - clock_begin) / CLOCKS_PER_SEC << endl;
  51. }
  52.  
  53. int main()
  54. {
  55. typedef int test_type;
  56.  
  57. rand_value = 1;
  58. test_func<test_type, func_method::mult>();
  59. rand_value = 1;
  60. test_func<test_type, func_method::log_or>();
  61.  
  62. return 0;
  63. }
Success #stdin #stdout 4.6s 5048KB
stdin
Standard input is empty
stdout
sum:  48828
time: 2.22886
sum:  48828
time: 2.36976