C++ implements a simple example of a statistical code runtime timer

  • 2020-05-26 09:46:07
  • OfStack

C++ implements a simple example of a statistical code runtime timer

1. Introduction

Here's a list of some of your favorite C++ timing codes from the Internet

2. Linux down to milliseconds


#include <sys/time.h> 
#include <iostream> 
#include <time.h> 
double get_wall_time() 
{ 
  struct timeval time ; 
  if (gettimeofday(&time,NULL)){ 
    return 0; 
  } 
  return (double)time.tv_sec + (double)time.tv_usec * .000001; 
} 
 
int main() 
{ 
  unsigned int t = 0; 
  double start_time = get_wall_time() 
  while(t++<10e+6); 
  double end_time = get_wall_time() 
  std::cout<<" The cycle time is :"<<end_time-start_time<<"ms"; 
  return 0; 
} 

3. Windows down to milliseconds


#include <windows.h> 
#include <iostream> 
 
int main() 
{ 
  DWORD start, stop; 
  unsigned int t = 0; 
  start = GetTickCount(); 
  while (t++ < 10e+6); 
  stop = GetTickCount(); 
  printf("time: %lld ms\n", stop - start); 
  return 0; 
} 

In the experiment, it seems that the getTickCount function has an error of 10 milliseconds.

4. Windows down to microseconds


//MyTimer.h// 
#ifndef __MyTimer_H__  
#define __MyTimer_H__  
#include <windows.h>  
 
class MyTimer 
{ 
private: 
  int _freq; 
  LARGE_INTEGER _begin; 
  LARGE_INTEGER _end; 
 
public: 
  long costTime;      //  Time spent ( Accurate to microseconds )  
 
public: 
  MyTimer() 
  { 
    LARGE_INTEGER tmp; 
    QueryPerformanceFrequency(&tmp);//QueryPerformanceFrequency() Effect: returns the frequency of a hardware-supported high precision counter.   
 
    _freq = tmp.QuadPart; 
    costTime = 0; 
  } 
 
  void Start()      //  Start the time   
  { 
    QueryPerformanceCounter(&_begin);// Get the initial value   
  } 
 
  void End()        //  The end of the timing   
  { 
    QueryPerformanceCounter(&_end);// Obtain termination value   
    costTime = (long)((_end.QuadPart - _begin.QuadPart) * 1000000 / _freq); 
  } 
 
  void Reset()      //  Timing of qing dynasty 0  
  { 
    costTime = 0; 
  } 
}; 
#endif  
 
//main.cpp 
#include "MyTimer.h" 
#include <iostream> 
 
 
int main() 
{ 
  MyTimer timer; 
  unsigned int t = 0;  
  timer.Start(); 
  while (t++ < 10e+5); 
  timer.End();  
  std::cout << " Time for: " << timer.costTime << "us"; 
  return 0 ; 
} 

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: