Advertisement
stream13

variable swap comparison

Aug 23rd, 2013
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include <iostream>
  2. #include <sys/time.h>                // for gettimeofday()
  3.  
  4. // g++ main.cpp -o swap_test -march=native -O2
  5.  
  6. using namespace std;
  7.  
  8. #define NUMSTEPS 1000000000
  9.  
  10. int main(){
  11.     timeval t1, t2, t3, t4;
  12.     unsigned int a = 32, b = 64, c = 0, i = 0;
  13.     double elapsedTime;
  14.  
  15.     gettimeofday(&t1, NULL);
  16.     for(i = 0; i < NUMSTEPS; ++i){
  17.         swap(a, b);
  18.     }
  19.  
  20.     gettimeofday(&t2, NULL);
  21.     for(i = 0; i < NUMSTEPS; ++i){
  22.         a^=b;
  23.         b^=a;
  24.         a^=b;
  25.     }
  26.  
  27.     gettimeofday(&t3, NULL);
  28.     for(i = 0; i < NUMSTEPS; ++i){
  29.         c = b;
  30.         b = a;
  31.         a = c;
  32.     }
  33.     gettimeofday(&t4, NULL);
  34.  
  35.     // compute and print the elapsed time in millisec
  36.     elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
  37.     elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms
  38.     cout << "swap\t" << elapsedTime << " ms.\n";
  39.  
  40.     elapsedTime = (t3.tv_sec - t2.tv_sec) * 1000.0;      // sec to ms
  41.     elapsedTime += (t3.tv_usec - t2.tv_usec) / 1000.0;   // us to ms
  42.     cout << "XOR\t" << elapsedTime << " ms.\n";
  43.  
  44.     elapsedTime = (t4.tv_sec - t3.tv_sec) * 1000.0;      // sec to ms
  45.     elapsedTime += (t4.tv_usec - t3.tv_usec) / 1000.0;   // us to ms
  46.     cout << "+var\t" << elapsedTime << " ms.\n";
  47.     cout<<a<<b<<c<<"\b\b\b\b\b\b";
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement