fork(1) download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <iostream>
  4. #include <chrono>
  5. #include <vector>
  6. class C{
  7. public: float hello;
  8. public: float hello2s[10];
  9. public: C(){
  10. hello=((double) rand() / (RAND_MAX))*10;
  11. for(int n=0;n<10;n++){
  12. hello2s[n]= ((double) rand() / (RAND_MAX))*10;
  13. }
  14. }
  15. public: float calculateCheap(){
  16. return hello;
  17. }
  18. public: float calculateExpensive(){
  19. float result=1;
  20. result=hello2s[0]*hello2s[1]*hello2s[2]*hello2s[3]*hello2s[4];
  21. return result;
  22. }
  23. };
  24. int main(){
  25. const int numTest=10000;
  26. C d[numTest];
  27. C* e[numTest];
  28. for(int n=0;n<numTest;n++){
  29. d[n]=C();
  30. e[n]=new C();
  31. }
  32. float accu=0;
  33. auto t1= std::chrono::system_clock::now();
  34. for(int n=0;n<numTest;n++){
  35. accu+=d[n].calculateExpensive(); //direct call
  36. }
  37. auto t2= std::chrono::system_clock::now();
  38. for(int n=0;n<numTest;n++){
  39. accu+=e[n]->calculateCheap(); //indirect call
  40. }
  41. auto t3= std::chrono::system_clock::now();
  42. std::cout<<"direct call time ="<<(t2-t1).count()<<std::endl;
  43. std::cout<<"indirect call time ="<<(t3-t2).count()<<std::endl;
  44. std::cout<<"print to disable compiler cheat="<<accu<<std::endl;
  45. }
  46.  
Success #stdin #stdout 0s 16440KB
stdin
Standard input is empty
stdout
direct call time =21637
indirect call time =23236
print to disable compiler cheat=3.17658e+07