fork download
  1. #include <vector>
  2. #include <iostream>
  3. #include <cmath>
  4. #include <algorithm>
  5. #include <sys/time.h>
  6. #include <inttypes.h>
  7.  
  8. using namespace std;
  9.  
  10. struct Big {
  11. int data[5];
  12. int id;
  13. Big(int _id): id(_id){}
  14. };
  15.  
  16. bool bigcmp(const Big& lhs, const Big& rhs) {return lhs.id > rhs.id;}
  17. bool bigcmpm1(const Big& lhs, const Big& rhs) {return lhs.id < rhs.id;}
  18. bool pbigcmp(const Big* lhs, const Big* rhs) {return lhs->id > rhs->id;}
  19. bool pbigcmpm1(const Big* lhs, const Big* rhs) {return lhs->id < rhs->id;}
  20.  
  21. typedef uint64_t u64;
  22. static u64 nsec() {
  23. struct timeval tv;
  24. if(gettimeofday(&tv, 0) < 0)
  25. return -1;
  26. return (u64)tv.tv_sec*1000*1000*1000 + tv.tv_usec*1000;
  27. }
  28.  
  29. const u64 nsec_in_sec = 1000*1000*1000;
  30. class stats {
  31. double n, M2, _mean;
  32. public:
  33. stats():n(0),M2(0),_mean(0){}
  34. stats& add(double x) {
  35. n++;
  36. double delta = x - _mean;
  37. _mean += delta/n;
  38. M2 += delta*(x-_mean);
  39. return *this;
  40. }
  41. double mean() {return _mean;}
  42. double stddev() {return sqrt(M2/n);}
  43. };
  44.  
  45.  
  46. int main(int, char**) {
  47. stats p,v;
  48. const int SZ = 500000;
  49. vector<Big> b;
  50. vector<Big*> pb;
  51. for (int i=0; i<SZ; i++) {
  52. b.push_back(Big(i));
  53. pb.push_back(new Big(i));
  54. }
  55. for (int times=10; times>0; times--) {
  56. u64 start = nsec();
  57. sort(b.begin(), b.end(), bigcmp);
  58. sort(b.begin(), b.end(), bigcmpm1);
  59. v.add(nsec()-start);
  60. }
  61. for (int times=10; times>0; times--) {
  62. u64 start = nsec();
  63. sort(pb.begin(), pb.end(), pbigcmp);
  64. sort(pb.begin(), pb.end(), pbigcmpm1);
  65. p.add(nsec()-start);
  66. }
  67. cout << "By value " << v.mean()/nsec_in_sec << " sec std "
  68. << v.stddev()/nsec_in_sec << " sec" << endl;
  69. cout << "By pointer " << p.mean()/nsec_in_sec << " sec std "
  70. << p.stddev()/nsec_in_sec << " sec" << endl;
  71. }
  72.  
Success #stdin #stdout 2.6s 18352KB
stdin
Standard input is empty
stdout
By value   0.118327 sec std 0.000353952 sec
By pointer 0.132589 sec std 0.00162196 sec