定时算法:clock()vs time()在C ++中 [英] Timing algorithm: clock() vs time() in C++

查看:193
本文介绍了定时算法:clock()vs time()在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于计算算法(大约以ms为单位),这两种方法中哪一种更好:

For timing an algorithm (approximately in ms), which of these two approaches is better:

clock_t start = clock();
algorithm();
clock_t end = clock();
double time = (double) (end-start) / CLOCKS_PER_SEC * 1000.0;

time_t start = time(0);
algorithm();
time_t end = time(0);
double time = difftime(end, start) * 1000.0;

此外,从Freenode的C ++频道的一些讨论中,我知道时钟的分辨率很差,因此对于(相对)快速算法,定时将为零。但是,它有更好的分辨率time()或clock()?

Also, from some discussion in the C++ channel at Freenode, I know clock has a very bad resolution, so the timing will be zero for a (relatively) fast algorithm. But, which has better resolution time() or clock()? Or is it the same?

推荐答案

这取决于你想要什么: time 测量实时,而 clock 测量当前进程所需的处理时间。如果你的进程睡眠了任何可观的时间,或者系统正忙于其他进程,那么两者会有很大的不同。

It depends what you want: time measures the real time while clock measures the processing time taken by the current process. If your process sleeps for any appreciable amount of time, or the system is busy with other processes, the two will be very different.

http://en.cppreference.com/w/cpp/chrono/c/clock

这篇关于定时算法:clock()vs time()在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆