如何在Matlab中正确衡量一段代码的执行时间?

时间:2019-01-11 14:17:29

标签: matlab time

我创建了一个函数,使用其使用功率方法来计算特征向量中心性。我使用了num_of_terms变量来确定计算次数,并且我正在尝试使用tic toc

在以下操作中计算执行时间
adj = [ 0 1 0 0 0 0 0 0 0 0 ;
    1 0 1 1 0 1 0 0 0 0 ;
    0 1 0 1 0 0 0 0 0 0 ;
    0 1 1 0 0 0 1 0 0 0 ;
    0 0 0 0 0 1 0 0 0 0 ;
    0 1 0 0 1 0 1 1 0 1 ;
    0 0 0 1 0 1 0 0 1 0 ;
    0 0 0 0 0 1 0 0 0 0 ;
    0 0 0 0 0 0 1 0 0 1 ;
    0 0 0 0 0 1 0 0 1 0 ;
  ];

x0 = ones(1,10);

time_Exe2 = zeros(1,10);
for i = 1 : 10
    [~,time_Exe2(i)] = cul_eigvector_sentrality_Power_Method(adj,x0,i);
end


function [eigvector_centrality , time_exe] = cul_eigvector_sentrality_Power_Method(adj,x0,num_of_terms)
   clear tic time_exe Xn
   %time = hat();
   tic;
   Xn = x0 * adj;
   for i = 1 : num_of_terms -1
      Xn = Xn * adj; 
   end
   Xn = Xn/norm(Xn);
   time_exe = toc;
   %time_exe = hat() - time ;
   eigvector_centrality = Xn;
end

我希望执行时间的结果会根据操作增加时间。 但是,随着尺寸的增加,时间越来越短。

#Time_execuson

0.000379
  0.000112
  0.000163
  0.000404
  0.000681
  0.000037
  0.000033
  0.000039
  0.000045
  0.000030

有人知道如何解决此问题吗?如果您有什么建议吗?

1 个答案:

答案 0 :(得分:0)

有两个原因:

  1. 事情太短了,无法准确衡量
  2. 您的大部分时间都花在了函数开始时清除变量上。为什么要这样做,这是完全没有用的操作。

因此,如果我修正了您的代码以进行准确的测量.....

adj = [ 0 1 0 0 0 0 0 0 0 0 ;
    1 0 1 1 0 1 0 0 0 0 ;
    0 1 0 1 0 0 0 0 0 0 ;
    0 1 1 0 0 0 1 0 0 0 ;
    0 0 0 0 0 1 0 0 0 0 ;
    0 1 0 0 1 0 1 1 0 1 ;
    0 0 0 1 0 1 0 0 1 0 ;
    0 0 0 0 0 1 0 0 0 0 ;
    0 0 0 0 0 0 1 0 0 1 ;
    0 0 0 0 0 1 0 0 1 0 ;
    ];

x0 = ones(1,10);

time_Exe2 = zeros(1,10);
for i = 1 : 10
    tic
    for jj = 1:100000
        [~,time_Exe2(i)] = cul_eigvector_sentrality_Power_Method(adj,x0,i);
    end
    toc
end


function [eigvector_centrality , time_exe] = cul_eigvector_sentrality_Power_Method(adj,x0,num_of_terms)
% clear tic time_exe Xn
%time = hat();
% start = tic;
Xn = x0 * adj;
for i = 1 : num_of_terms -1
    Xn = Xn * adj;
end
Xn = Xn/norm(Xn);
% time_exe = toc(start);
%time_exe = hat() - time ;
time_exe = 0;
eigvector_centrality = Xn;
end

我知道...

Elapsed time is 0.035333 seconds.
Elapsed time is 0.050844 seconds.
Elapsed time is 0.068729 seconds.
Elapsed time is 0.081161 seconds.
Elapsed time is 0.094741 seconds.
Elapsed time is 0.118831 seconds.
Elapsed time is 0.132486 seconds.
Elapsed time is 0.137858 seconds.
Elapsed time is 0.152711 seconds.
Elapsed time is 0.169682 seconds.

您正在寻找的结果。请注意,这些时间是循环执行该操作100,000次所需的时间。