计算运行时间
- LINK:https://zhuanlan.zhihu.com/p/54665895
1) clock()
返回从 开启这个程序进程 到 程序中调用clock()函数 时之间的CPU时钟计时单元(clock tick)数(挂钟时间),返回单位是毫秒 ```cpp // time.h
clock_t start,end;
start = clock();
/ code /
end = clock();
cout<<”time = “<<double(end-start)/CLOCKS_PER_SEC<<”s”<<endl;
<a name="h8Rr0"></a>
#### 2)GetTickCount() // windows api
返回从操作系统启动到现在所经过的毫秒数(ms), 精确度在16ms左右,最精确也不会精确过10ms
```cpp
#include <windows.h> //引入头文件
int main()
{
DWORD t1,t2;
t1 = GetTickCount();
fun() //需计时的函数
t2 = GetTickCount();
cout<<"time = "<<((t2-t1)*1.0/1000)<<endl; //输出时间(单位:s)
}
3) QueryPerformanceCounter() // windows api
#include <windows.h> //引入头文件
int main()
{
LARGE_INTEGER t1,t2,tc;
QueryPerformanceFrequency(&tc);
QueryPerformanceCounter(&t1);
fun() //需计时的函数
QueryPerformanceCounter(&t2);
time=(double)(t2.QuadPart-t1.QuadPart)/(double)tc.QuadPart;
cout<<"time = "<<time<<endl; //输出时间(单位:s)
}
4) gettimeofday() // linux
//timeval结构定义为:
struct timeval{
long tv_sec; /*秒*/
long tv_usec; /*微秒*/
};
//timezone 结构定义为:
struct timezone{
int tz_minuteswest; /*和Greenwich 时间差了多少分钟*/
int tz_dsttime; /*日光节约时间的状态*/
};
#include <sys/time.h> //引入头文件
int main()
{
struct timeval t1,t2;
double timeuse;
gettimeofday(&t1,NULL);
fun();
gettimeofday(&t2,NULL);
timeuse = (t2.tv_sec - t1.tv_sec) + (double)(t2.tv_usec - t1.tv_usec)/1000000.0;
cout<<"time = "<<timeuse<<endl; //输出时间(单位:s)
}