fork(1) download
  1. #include <iostream>
  2. #include <random>
  3. #include <chrono>
  4. #include <algorithm>
  5. using namespace std;
  6. using namespace std::chrono;
  7.  
  8. const int sz = 500000;
  9. const int rpt = 2000;
  10. int n;
  11. double sum=0;
  12.  
  13. void f1(double *arr) {
  14. for (int i = 0; i < n; i++)
  15. sum += arr[i];
  16. }
  17.  
  18. void f2(double *arr) {
  19. for (int i = 0; i < n; i++)
  20. if (arr[i])
  21. sum += arr[i];
  22. }
  23.  
  24. int main() {
  25. mt19937_64 engine(time(0));
  26. uniform_real_distribution<> distri(-1000000.0, +1000000.0);
  27. uniform_int_distribution<int> distn(0,sz-1);
  28. volatile double d;
  29.  
  30. n = sz;
  31. double *arr = new double[n];
  32. for (int i=0; i<sz/2; i++) { // play with density here
  33. int k = distn(engine);
  34. arr[k]=distri(engine);
  35. }
  36. int zero = count(arr, arr+n, 0.0);
  37. cout << zero << " null items, " << (double)zero/sz*100.0 << "%"<<endl;
  38.  
  39. high_resolution_clock::time_point t1=high_resolution_clock::now();
  40. for (int j=0; j<rpt; j++) {
  41. sum=0;
  42. f1(arr);
  43. d=sum;
  44. }
  45. high_resolution_clock::time_point t2=high_resolution_clock::now();
  46. cout << duration_cast<milliseconds>(t2-t1).count() <<endl;
  47. cout<<"\t"<<sum<<endl;
  48.  
  49. high_resolution_clock::time_point t3=high_resolution_clock::now();
  50. for (int j=0; j<rpt; j++) {
  51. sum=0;
  52. f2(arr);
  53. d=sum;
  54. }
  55. high_resolution_clock::time_point t4=high_resolution_clock::now();
  56. cout << duration_cast<milliseconds>(t4-t3).count() <<endl;
  57. cout<<"\t"<<sum<<endl;
  58.  
  59. return 0;
  60. }
Success #stdin #stdout 4.42s 19144KB
stdin
Standard input is empty
stdout
303083 null items, 60.6166%
797
	3.88259e+08
3692
	3.88259e+08