如何为 MatLab 脚本的每一行计时?

How to time each line of a MatLab script?

假设我们有一个循环:

for i = 1:1000
    A
    B
    C
end

...我想找出 CPU 使用范围。

A、B、C 是 MatLab 语句而不是函数,所以 (IIUC) 我不能使用分析器。

其实我还有十几行要讲。

明显冗长的方法是:

s = zeros(50, 1);
t = cputime;

for ...
    A
    s(1) = s(1) + (cputime-t);  t = cputime;
    B
    s(2) = s(2) + (cputime-t);  t = cputime;
    :

...这不是 坏,我想。

但是可以改进吗?


我想这样做:

t = zeros(50, 1);
e(t,0); % reset
for i = 1:1000
    A
    e(1);
    B
    e(2);
    C
    e(3);
end

...与:

function e(t, k)
    if k==0
        last_cputime = cputime;
        return
    end
    t(k) = t(k) + (cputime-last_cputime);
    last_cputime = cputime;
end

但是它没有看到t,所以我必须通过它。

它也不记得调用之间的 last_cputime,所以我也需要传递它。

所以e(last_cputime,t,1)

比较难看。我尝试使用内联函数:

e = @(k) eval( 't(k) = t(k) + (cputime-last_cputime);  cputime = last_cputime;' );

但我也无法正常工作:

K>> t = zeros(3,1)
t =
     0
     0
     0


K>> eval( 't(1) = 3' )
t =
     3
     0
     0


K>> e = @(k) eval( 't(k) = 3;' )
e =
  function_handle with value:

    @(k)eval('t(k) = 3;')


K>> e(1)
Attempt to add "t" to a static workspace.
 See Variables in Nested and Anonymous Functions.

Error in pi_test>@(k)eval('t(k) = 3;')

我想知道是否还有其他选择:

for i = 1:1000
    e('A');
    e('B');
    e('C');
end

但是怎么编码起来e

有什么方法可以避免通过复制造成可怕的丑陋?

处理这个的 classdef 怎么样?

您可以将其另存为mtime.m

classdef mtime < handle
    properties 
        times
    end
    properties (Access = private)
        t
    end

    methods
        function obj = mtime() %initialize
            obj.t=cputime;
            obj.times=[];
        end
        function time(obj)
            obj.times(end+1) = cputime-obj.t;
            obj.t = cputime;
        end
    end
end

然后您可以使用 T=mtime(); 初始化并通过调用 time(T); 为您的代码计时。代码完成后,可以在 T.times.

中找到计时