我想打印我的函数的运行时间。由于某种原因,我的计时器总是返回 0。谁能告诉我为什么?
double RunningTime(clock_t time1, clock_t time2)
{
double t=time1 - time2;
double time = (t*1000)/CLOCKS_PER_SEC;
return time;
}
int main()
{
clock_t start_time = clock();
// some code.....
clock_t end_time = clock();
std::cout << "Time elapsed: " << double(RunningTime(end_time, start_time)) << " ms";
return 0;
}
我尝试使用gettimeofday
它仍然返回0。
double get_time()
{
struct timeval t;
gettimeofday(&t, NULL);
double d = t.tv_sec + (double) t.tv_usec/100000;
return d;
}
int main()
{
double time_start = get_time();
//Some code......
double time_end = get_time();
std::cout << time_end - time_start;
return 0;
}
还尝试使用chrono
它给了我各种构建错误:
- 错误:#error 该文件需要编译器和库支持
即将推出的 ISO C++ 标准,C++0x。目前该支持
实验性的,并且必须使用 -std=c++0x 或 -std=gnu++0x 启用
编译器选项。
- 警告:'auto' 将改变 C++0x 中的含义;请删除它
- 错误:ISO C++ 禁止声明“t1”且无类型错误:
'std::chrono' 尚未声明
-
错误:请求“(t2 - t1)”中的成员“count”,其值为
非类类型“int”
int main()
{
自动 t1 = std::chrono::high_resolution_clock::now();
//Some code......
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "Time elapsed: " << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count() << " milliseconds\n";
return 0;
}
计时器滴答约等于 1/CLOCKS_PER_SEC 秒,即毫秒分辨率。要查看实数(非零)数字,您应该调用一个非常长的时间函数或使用另一个具有更高时间分辨率设施的库:
- 新的 c++11x 库
chrono
(使用 MSVS 2012)
-
boost::chrono
(不幸的是,该库引用了很多其他库)
- POSIX函数gettimeofday,这为您提供 1 微秒的时间分辨率
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)