在有的函数中,因为不确定是在哪里多耗费了时间导致的卡顿,所以可以使用下面这些方法获取函数执行时间,以此来判断是哪部分拖慢了系统的执行速度。
这里给出一个demo,可以仿照着使用
#include <iostream>
#include <vector>
#include <time.h>
//测试函数
void fun()
{
for (int i=0; i<10000; i++) {
std::vector<int> v;
for (int i=0; i<10000; i++) {
v.push_back(i);
}
for (int i=0; i<10000; i++) {
v.pop_back();
}
}
}
int main(int argc, const char * argv[]) {
std::cout << "Hello, World!\n";
///1 精确到秒
time_t start_time,end_time;
start_time=time(NULL);
fun();
end_time=time(NULL);
printf("%f\n",difftime(start_time, end_time));
///end
///2 精确到毫秒
double cost_time;
clock_t start,end;
start=clock();
fun();
end=clock();
cost_time=(double)((end-start)/CLOCKS_PER_SEC);
printf("%f\n",cost_time);
///3 精确到微秒
//需要包含<windows.h> 头文件,这个只能在windows上面使用
// #include <windows.h>
// LARGE_INTEGER time_start, time_end;
// LARGE_INTEGER frequency;
// QueryPerformanceFrequency(&frequency);//获取处理频率
// QueryPerformanceCounter(&time_start); //获取起始时间
// //do something
// QueryPerformanceCounter(&time_end); //获取终止时间
// cout<<time_end.u.HighPart<<' '<<time_end.u.LowPart<<endl;
// //VC6.0的环境不支持直接"cout<<"64位的整数
// printf("It's used %I64d, the frequency is %I64dHz/s\n",
// time_end.QuadPart - time_start.QuadPart, frequency);
// //耗时计算公式(运算结果为秒):
// //((time_end.QuadPart-time_start.QuadPart)/frequency.QuadPart)
// //具体用法可以参考更详细的资料
return 0;
}版权属于:东哥笔记 - DongGe.org
本文链接:https://blog.dongge.org/210.html
本文采用知识共享署名4.0 国际许可协议进行许可。转载或大段使用必须添加本文链接,否则您将构成侵权!
微信公众号: 东哥org
