Window系统下C/C++程序毫秒级和微秒级执行时间获取方法

一、使用clock()函数,获取毫秒级(ms)时间[1]

#include //clock()头文件

time_t start = clock();

  {statement section}//测试代码段

time_t end = clock();

printf("the running time is:%fs\n", double(end -start)/CLOCKS_PER_SEC); //秒

 

二、基于CPU级的方法,获取微秒级(us)时间[2,3]

#include

#include

LARGE_INTEGERR nFreq;

LARGE_INTEGER t1;

LARGE_INTEGER t2;

double dt;

QueryPerformanceFrequency(&nFreq);

QueryPerformanceCounter(&t1);

 {statementsection}//测试代码段

QueryPerformanceCounter(&t2);

dt =(t2.QuadPart -t1.QuadPart)/(double)nFreq.QuadPart;

cout<<"Running time:"<

 

备注:可以在代码段添加Sleep()函数测试,如下两个测试实例。

例1:500ms,ms级时间获取

#include //clock()头文件

time_t start = clock();

  Sleep(500);//500ms

time_t end = clock();

printf("the running time is:%fms\n", double(end -start));

 运行结果,如下:

the running time is :501.000000ms


例2: 5ms测试,us时间获取

#include// QueryPerformanceFrequency,QueryPerformanceCounter头文件

#include

LARGE_INTEGER  nFreq,t1,t2;

double dt;

QueryPerformanceFrequency(&nFreq);

QueryPerformanceCounter(&t1);

Sleep(5);//5ms,其中1ms=1000us

QueryPerformanceCounter(&t2);

 dt =(t2.QuadPart - t1.QuadPart)/(double)nFreq.QuadPart;

cout<<"Running time :"<

 运行结果,如下:

Running time : 5162.22us

 

参考:

[1] http://blog.sina.com.cn/s/blog_71a211bf0101mugn.html

[2] http://blog.sina.com.cn/s/blog_9700e68d0100wfh4.html

[3] http://www.cppblog.com/deane/articles/113151.html

 
  
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
  

你可能感兴趣的:(C/C++,软件学习)