fork download
  1. #include <iostream>
  2. #include <tuple>
  3. #include <chrono>
  4. using namespace std;
  5. using namespace std::chrono;
  6.  
  7. void safe_swap(int* a, int* b) {
  8. if (a != b)
  9. *b ^= *a ^= *b, *a ^= *b;
  10. }
  11. void classic_swap(int*a, int*b) {
  12. if (a!=b) {
  13. int tmp;
  14. tmp=*a;*a=*b;*b=tmp;
  15. }
  16. }
  17. void modern_swap(int*a, int*b) {
  18. if (a!=b)
  19. tie(*a,*b)=make_pair(*b,*a);
  20. }
  21.  
  22. long long benchmark(void(*f)(int*,int*)) {
  23. int a,b;
  24. long long mytime;
  25. high_resolution_clock::time_point t = high_resolution_clock::now();
  26. a = rand();
  27.  
  28. for (unsigned i=0; i<200000000; i++) {
  29. b = rand();
  30. f(&a,&b);
  31. }
  32. high_resolution_clock::time_point t2 = high_resolution_clock::now();
  33. mytime = duration_cast<milliseconds>(t2 - t).count();
  34. return mytime;
  35. }
  36.  
  37. int main() {
  38. auto t1 = benchmark (safe_swap);
  39. auto t2 = benchmark (modern_swap);
  40. cout << "xor: "<<t1<<" ms" <<endl;
  41. cout << "modern:"<<t2<<" ms" <<endl;
  42. cout << "rel xor time: " << static_cast<double>(t1)/t2*100 <<"%"<<endl;
  43. return 0;
  44. }
Success #stdin #stdout 3.3s 15232KB
stdin
Standard input is empty
stdout
xor:   1708 ms
modern:1606 ms
rel xor time: 106.351%