Guest User

Untitled

a guest
May 6th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. #include <time.h>
  2. #include <stdio.h>
  3. #include <stdint.h>
  4.  
  5. int Log2FloorBASE(uint32_t n) {
  6. if (n == 0)
  7. return -1;
  8. int log = 0;
  9. uint32_t value = n;
  10. for (int i = 4; i >= 0; --i) {
  11. int shift = (1 << i);
  12. uint32_t x = value >> shift;
  13. if (x != 0) {
  14. value = x;
  15. log += shift;
  16. }
  17. }
  18. return log;
  19. }
  20.  
  21. int Log2FloorNEW(uint64_t n) {
  22. if (!n) return -1;
  23. int log = 0;
  24. for (int i = 5; i >= 0; ++i) {
  25. int shift = 1 << i;
  26. if (n >> shift) {
  27. log += shift;
  28. if (!(n >>= shift)) break;
  29. }
  30. }
  31. return log;
  32. }
  33.  
  34.  
  35. int main() {
  36. time_t t = time(NULL);
  37. printf("base: %d\n", Log2FloorBASE(128));
  38. printf(" took: %ld seconds\n", time(NULL) - t);
  39.  
  40. t = time(NULL);
  41. printf("new: %d\n", Log2FloorNEW(128));
  42. printf(" took: %ld seconds\n", time(NULL) - t);
  43.  
  44. return 0;
  45. }
  46.  
  47.  
  48. $ g++ -o test test.cc && ./test
  49. base: 7
  50. took: 0 seconds
  51. new: 7
  52. took: 9 seconds
Advertisement
Add Comment
Please, Sign In to add comment