Posted By

browny on 09/03/10


Tagged

timer


Versions (?)

High accuracy program timer


 / Published in: C++
 

URL: http://cplus.about.com/od/howtodothingsi2/a/timing.htm

  1. // How to use
  2.  
  3. CStopWatch s;
  4. s.startTimer();
  5.  
  6. // put the code which you want to measure here //
  7.  
  8. s.stopTimer();
  9. double mtime = s.getElapsedTime() * 1000;
  10.  
  11.  
  12. // hr_time.h
  13. #include <windows.h>
  14.  
  15. typedef struct {
  16. LARGE_INTEGER start;
  17. LARGE_INTEGER stop;
  18. } stopWatch;
  19.  
  20. class CStopWatch {
  21.  
  22. private:
  23. stopWatch timer;
  24. LARGE_INTEGER frequency;
  25. double LIToSecs( LARGE_INTEGER & L) ;
  26. public:
  27. CStopWatch() ;
  28. void startTimer( ) ;
  29. void stopTimer( ) ;
  30. double getElapsedTime() ;
  31. };
  32.  
  33.  
  34. // hr_time.cpp
  35. #include <windows.h>
  36.  
  37. #ifndef hr_timer
  38. #include "hr_time.h"
  39. #define hr_timer
  40. #endif
  41.  
  42. double CStopWatch::LIToSecs( LARGE_INTEGER & L) {
  43. return ((double)L.QuadPart /(double)frequency.QuadPart) ;
  44. }
  45.  
  46. CStopWatch::CStopWatch(){
  47. timer.start.QuadPart=0;
  48. timer.stop.QuadPart=0;
  49. QueryPerformanceFrequency( &frequency ) ;
  50. }
  51.  
  52. void CStopWatch::startTimer( ) {
  53. QueryPerformanceCounter(&timer.start) ;
  54. }
  55.  
  56. void CStopWatch::stopTimer( ) {
  57. QueryPerformanceCounter(&timer.stop) ;
  58. }
  59.  
  60. double CStopWatch::getElapsedTime() {
  61. LARGE_INTEGER time;
  62. time.QuadPart = timer.stop.QuadPart - timer.start.QuadPart;
  63. return LIToSecs( time) ;
  64. }

Report this snippet  

You need to login to post a comment.