fork(19) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int msb(int x) {
  5. union { double a; int b[2]; };
  6. a = x;
  7. return (b[1] >> 20) - 1023;
  8. }
  9.  
  10. int highestOneBit(int i) {
  11. // HD, Figure 3-1
  12. i |= (i >> 1);
  13. i |= (i >> 2);
  14. i |= (i >> 4);
  15. i |= (i >> 8);
  16. i |= (i >> 16);
  17. return i - ((unsigned)i >> 1);
  18. }
  19.  
  20. int main() {
  21. double t1, t2;
  22. const int lim = 200 * 1000 * 1000;
  23. {
  24. t1 = clock();
  25. for (int i = 0; i < lim; i++) {
  26. int t = msb(i);
  27. if (t == -42) return 1;
  28. }
  29. t2 = clock();
  30. cout << (t2 - t1) / 1000.0 << endl;
  31. }
  32. {
  33. t1 = clock();
  34. for (int i = 0; i < lim; i++) {
  35. int t = highestOneBit(i);
  36. if (t == -42) return 1;
  37. }
  38. t2 = clock();
  39. cout << (t2 - t1) / 1000.0 << endl;
  40. }
  41. }
  42.  
Success #stdin #stdout 2.47s 3296KB
stdin
Standard input is empty
stdout
1510
950