kalmanfans's Blog

模式识别 非线性预测 复杂网络 Following your heart

Matlab runtime运行时间计算

kalmanfans posted @ 2012年5月14日 15:06 in Matlab , 2980 阅读

 

通常在算法研究中要对比算法的效率。比较算法效率的一种重要指标,就是考量不同算法在计算处理相同规模的实验数据时,需要的计算时间。本文在这里罗列三种常见的matlab 程序运行时间计算方法。

 

当然这个对于只有几秒钟的小程序没有什么意义,但是对于大程序就有很重要的意义了。

注意:三种方法由于使用原理不一样,得到结果可能有一定的差距!

1、tic和toc组合(使用最多的)

计算tic和toc之间那段程序之间的运行时间,它的经典格式为

  1. tic
  2. 。。。。。。。。。。
  3. toc

复制代码

换句话说程序,程序遇到tic时Matlab自动开始计时,运行到toc时自动计算此时与最近一次tic之间的时间。这个有点拗口,下面我们举个例子说明

  1. % by dynamic of Matlab技术论坛
  2. % see also http://www.matlabsky.com
  3. % contact me matlabsky@gmail.com
  4. % 2009-08-18 12:08:47
  5. clc
  6. tic;%tic1
  7. t1=clock;
  8. for i=1:3
  9. tic ;%tic2
  10. t2=clock;
  11. pause(3*rand)
  12. %计算到上一次遇到tic的时间,换句话说就是每次循环的时间
  13. disp(['toc计算第',num2str(i),'次循环运行时间:',num2str(toc)]);
  14. %计算每次循环的时间
  15. disp(['etime计算第',num2str(i),'次循环运行时间:',num2str(etime(clock,t2))]);
  16. %计算程序总共的运行时间
  17. disp(['etime计算程序从开始到现在运行的时间:',num2str(etime(clock,t1))]);
  18. disp('======================================')
  19. end
  20. %计算此时到tic2的时间,由于最后一次遇到tic是在for循环的i=3时,所以计算的是最后一次循环的时间
  21. disp(['toc计算最后一次循环运行时间',num2str(toc)])
  22. disp(['etime程序总运行时间:',num2str(etime(clock,t1))]);

复制代码

运行结果如下,大家可以自己分析下

  1. toc计算第1次循环运行时间:2.5628
  2. etime计算第1次循环运行时间:2.562
  3. etime计算程序从开始到现在运行的时间:2.562
  4. ======================================
  5. toc计算第2次循环运行时间:2.8108
  6. etime计算第2次循环运行时间:2.813
  7. etime计算程序从开始到现在运行的时间:5.375
  8. ======================================
  9. toc计算第3次循环运行时间:2.0462
  10. etime计算第3次循环运行时间:2.046
  11. etime计算程序从开始到现在运行的时间:7.421
  12. ======================================
  13. toc计算最后一次循环运行时间2.0479
  14. etime程序总运行时间:7.421

复制代码

2、etime(t1,t2)并和clock配合

来计算t1,t2之间的时间差,它是通过调用windows系统的时钟进行时间差计算得到运行时间的,应用的形式

  1. t1=clock;
  2. 。。。。。。。。。。。
  3. t2=clock;
  4. etime(t2,t1)

复制代码

至于例子我就不举了,因为在上面的例子中使用了etime函数了

3、cputime函数来完成

使用方法和etime相似,只是这个是使用cpu的主频计算的,和前面原理不同,使用格式如下

  1. t0=cputime
  2. 。。。。。。。。。。。。。
  3. t1=cputime-t0

复制代码

上面说到了三种方法,都是可以进行程序运行时间计算的,但是Matlab官方推荐使用tic/toc组合,When timing the duration of an event, use the tic and toc functions instead of clock or etime.

至于大家可以根据自己的喜好自己选择,但是使用tic/toc的时候一定要注意,toc计算的是与最后一次运行的tic之间的时间,不是第一个tic,更不是第二个。。。。。

Avatar_small
mts files 说:
2017年8月20日 09:20

我試的結果是無法下載

Avatar_small
Emma 说:
2023年1月19日 11:49

As a programmer, it is essential to understand the runtime of Matlab programs. Calculating the running time of your code can be a difficult task, but it can also be extremely useful in Full Spectrum CBD understanding the performance of your programs. With the right techniques, you can accurately measure the time it takes for a Matlab program to execute and make improvements where necessary. Knowing the running time of your Matlab code can help you optimize the performance of your programs and ensure they are running at their best.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter