1
0

celllinux.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <time.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <sys/time.h>
  5. #include <sys/types.h>
  6. #include <spu_mfcio.h>
  7. static long myround(double u)
  8. {
  9. long result = u;
  10. while (result + 0.5 < u) result += 1;
  11. while (result - 0.5 > u) result -= 1;
  12. return result;
  13. }
  14. static long long microseconds(void)
  15. {
  16. struct timeval t;
  17. gettimeofday(&t,(struct timezone *) 0);
  18. return t.tv_sec * (long long) 1000000 + t.tv_usec;
  19. }
  20. static long long timebase(void)
  21. {
  22. unsigned long long result;
  23. result = -spu_read_decrementer();
  24. return 0xffffffff & result;
  25. }
  26. static double cpufrequency = 0;
  27. static long tbcycles = 0;
  28. static double guesstbcycles(void)
  29. {
  30. long long tb0; long long us0;
  31. long long tb1; long long us1;
  32. tb0 = timebase();
  33. us0 = microseconds();
  34. do {
  35. tb1 = timebase();
  36. us1 = microseconds();
  37. } while (us1 - us0 < 10000 || tb1 - tb0 < 1000);
  38. if (tb1 <= tb0) return 0;
  39. tb1 -= tb0;
  40. us1 -= us0;
  41. return (cpufrequency * 0.000001 * (double) us1) / (double) tb1;
  42. }
  43. static void init(void)
  44. {
  45. int loop;
  46. double guess1;
  47. double guess2;
  48. spu_write_decrementer(0xffffffff);
  49. cpufrequency = 3192000000.0;
  50. for (loop = 0;loop < 100;++loop) {
  51. guess1 = guesstbcycles();
  52. guess2 = guesstbcycles();
  53. tbcycles = myround(guess1);
  54. if (guess1 - tbcycles > 0.1) continue;
  55. if (tbcycles - guess1 > 0.1) continue;
  56. if (guess2 - tbcycles > 0.1) continue;
  57. if (tbcycles - guess2 > 0.1) continue;
  58. return;
  59. }
  60. tbcycles = 0;
  61. }
  62. long long cpucycles_celllinux(void)
  63. {
  64. if (!tbcycles) init();
  65. return timebase() * tbcycles;
  66. }
  67. long long cpucycles_celllinux_persecond(void)
  68. {
  69. if (!tbcycles) init();
  70. return cpufrequency;
  71. }