`
love19820823
  • 浏览: 934820 次
文章分类
社区版块
存档分类
最新评论

C++高精度定时器

 
阅读更多
  1. ///////////////////////////////////////////////////////////////////////////////
  2. //KTimer.h
  3. //
  4. //WindowsGraphicsProgrammingWin32GDIandDirectDraw®
  5. //FengYuan
  6. //Publisher:PrenticeHallPTR
  7. //FirstEditionDecember01,2000
  8. //
  9. //高精度纳秒计时器,最后修改:
  10. //2008-12bycheungmine@gmail.com
  11. ///////////////////////////////////////////////////////////////////////////////
  12. /*Usage:
  13. intmain()
  14. {
  15. KTimerkt;
  16. unsignedintcpu_speed=kt.CPUSpeedMHz();
  17. kt.Start();
  18. Sleep(1234);
  19. unsignedintelapsed_cyc=(unsignedint)kt.Stop();
  20. printf("CPUSpeed:%.2fGhz.Elapsed%ldCPUCycles(%ldNanosecond)/n",
  21. cpu_speed/1000.f,
  22. elapsed_cyc,
  23. KTimer::CyclesToNanos(elapsed_cyc,cpu_speed));
  24. }
  25. */
  26. #pragmaonce
  27. #ifndefSTRICT
  28. #defineSTRICT
  29. #endif
  30. #ifndefWIN32_LEAN_AND_MEAN
  31. #defineWIN32_LEAN_AND_MEAN
  32. #endif
  33. #include<windows.h>
  34. inlineunsigned__int64GetCycleCount(void)
  35. {
  36. _asm_emit0x0F
  37. _asm_emit0x31
  38. }
  39. classKTimer
  40. {
  41. unsigned__int64m_startcycle;
  42. public:
  43. unsigned__int64m_overhead;//ClockCycles
  44. KTimer(void)
  45. {
  46. m_overhead=0;
  47. Start();
  48. m_overhead=Stop();
  49. }
  50. //启动CPU时钟
  51. voidStart(void)
  52. {
  53. m_startcycle=GetCycleCount();
  54. }
  55. //停止CPU时钟,返回自上一次启动的时钟周期数
  56. unsigned__int64Stop(void)
  57. {
  58. returnGetCycleCount()-m_startcycle-m_overhead;
  59. }
  60. //把以CPU周期数转为纳秒
  61. unsigned__int64staticCyclesToNanos(unsigned__int64time_cycles,unsignedintspeed_mhz)
  62. {
  63. returntime_cycles*1000/speed_mhz;
  64. }
  65. //把以CPU周期数转为毫秒
  66. unsigned__int64staticCyclesToMillis(unsigned__int64time_cycles,unsignedintspeed_mhz)
  67. {
  68. returntime_cycles/speed_mhz/1000;
  69. }
  70. //1GHz=1000MHz
  71. unsignedintCPUSpeedMHz()
  72. {
  73. Start();
  74. Sleep(1000);
  75. unsigned__int64cputime=Stop();
  76. return(unsignedint)(cputime/1000000);
  77. }
  78. };
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics