tic/toc/cputime测试时间的区别

cputime测试代码运行时间可能不及tic/toc准确是众所周知的事情。本文并非旧话重提,而是期望起到抛砖引玉的效果,从而找到cputime与tic/toc内在的区别。望不吝赐教!

用tic/toc测试如下代码
  1. tic
  2. pause(10);
  3. t=toc
复制代码
会发现matlab处于busy状态并持续10秒,然后输出:

t =

   10.0007

然而用如下cputime测试:
  1. t1=cputime;
  2. pause(10);
  3. t2=cputime;
  4. t=t2-t1
复制代码
会发现matlab也会处于busy状态并持续10秒,然后输出:

t =

    0.1875

为何差别如此巨大? 于是本人阅读了help,发现了:

Using tic and toc Versus the cputime Function

Although it is possible to measure performance using the cputime function, it is recommended that you use the tic and toc functions for this purpose exclusively. It has been the general rule for CPU-intensive calculations run on Microsoft Windows machines that the elapsed time using cputime and the elapsed time using tic and toc are close in value, ignoring any first time costs. There are cases however that show a significant difference between these two methods. For example, in the case of a Pentium 4 with hyperthreading running Windows, there can be a significant difference between the values returned by cputime versus tic and toc.


原来Mathworks自己也是推荐用tic toc,而非cputime,他们也发现了超线程奔四CPU用cputime测试时间跟tic toc差距很大,根据我个人的理解,这应该跟CPU多核间运算分配(多核CPU情况)、多线程之间运算分配(超线程CPU),以及CPU内部运算优化等多种因素有关。cputime测试的并非 代码实际执行时间,而是 CPU实际运行的时间。通过CPU内部多核间任务调度、线程间调动、cpu自身优化(如被称为turbo睿频的软超频技术等)等,每个cpu实际运行时间会大大低于代码执行时间,因而也就出现了cputime测试时间大大低于tic/toc的时间。比如你的电脑是双核同时还支持超线程,那么你用cputime测试的时间最大不会超过代码运行时间的1/4,实际情况中恐怕会更小。

然而,tic/toc是直接测试 代码实际执行时间,不论cpu有多少内核、多少线程、做何种优化,tic/toc都会给出代码实际运行时间的总和,因此tic/toc可以比较准确反映代码的真实运行时间。正因为如此,Mathworkss自己也是推荐用tic toc,而非cputime。

如今是多核的时代,并且Intel绝大多数cpu同时支持超线程,稍微高端一定的cpu都支持turbo技术,那么cputime测试的时间恐怕只会更加不准,所以,还是用tic toc把

以上纯属个人观点,欢迎批评指正,以期进步!

猜你喜欢

转载自blog.csdn.net/LucyLiHHU/article/details/78583708
toc
今日推荐