方法1,clock()函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock)
常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元
c++的头文件ctime中的库函数clock()提供了测试函数运行时间的方法:
1、clock()返回类型为clock_t类型
2、clock_t实际为long 类型, typedef long clock_t
3、clock()函数,返回从 开启这个程序进程到程序中调用clock()函数时之间的CPU时钟计时单元(clocktick)数(挂钟时间),返回单位是毫秒
4、可以用常量CLOCKS_PER_SEC,这个常量表示每一秒(per second)有多少个时钟计时单元
实例代码如下:
#include <iostream>
#include <ctime>
using namespace std;
int main(){
clock_t start, end;
start = clock();
//如果函数执行时间少的话,可能最后测出的结果为0,因为现在机子的运行速度很快
for(int j = 0; j < 1000; j++)
for(int i = 0; i < 1000000; i++){
}
end = clock();
cout << (double)(end - start) / CLOCKS_PER_SEC << endl;
return 0;
}
运行结果:2.562
方法2:timeGetTime()函数以毫秒计的系统时间。该时间为从系统开启算起所经过的时间,是windows api
Code:
void test3()
{
DWORD t1,t2;
t1 = timeGetTime();
foo();//dosomething
t2 = timeGetTime();
printf("Use Time:%f\n",(t2-t1)*1.0/1000);
}
前提:头文件中要加windows.h
并且在文件头中要加
#pragmacomment(lib,"winmm.lib")
方法3,QueryPerformanceCounter()这个函数返回高精确度性能计数器的值,它可以以微妙为单位计时.但是QueryPerformanceCounter()确切的精确计时的最小单位是与系统有关的,所以,必须要查询系统以得到QueryPerformanceCounter()返回的嘀哒声的频率.QueryPerformanceFrequency()提供了这个频率值,返回每秒嘀哒声的个数.
前提:头文件中加上windows.h
Code:
void test4()
{
LARGE_INTEGER t1,t2,tc;
QueryPerformanceFrequency(&tc);
QueryPerformanceCounter(&t1);
foo();//dosomething
QueryPerformanceCounter(&t2);
printf("Use Time:%f\n",(t2.QuadPart - t1.QuadPart)*1.0/tc.QuadPart);
}