【发布时间】:2023-04-02 18:08:01
【问题描述】:
我想打印我的函数的运行时间。出于某种原因,我的计时器总是返回 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; }
【问题讨论】:
-
如果您想要良好的分辨率,请考虑使用
<chrono>。您可以轻松地为单位指定毫秒而不是计算它。 -
在 *nix 系统上,尝试
gettimeofday()以获得高分辨率时间(微秒)。 -
如果你没有 C++11,你可以考虑在 Linux 上使用
clock_gettime(使用CLOCK_MONOTONIC_HR),或者在大多数其他 UNIX 变体上考虑gethrtime,在 Windows 上考虑QueryPerformanceCounter. -
@chris 我将如何实现
<chrono>?我很快就用谷歌搜索了它,但无法快速弄清楚如何将它放入我的程序中而不会导致构建错误。我用std::chrono::time_point<Clock> time_point -
@Fourthmeal70,我明白了,您的编译器选项中需要
-std=c++11或-std=c++0x标志。