Ηow to properly measure the execution time of a piece of code

1 回表示 (過去 30 日間)
John Blue
John Blue 2019 年 1 月 11 日
コメント済み: John Blue 2019 年 1 月 12 日
I've created a function to calculate it eigenvector centrality with its use power method. I used the variable num_of_terms that determines the count of the calculations.
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
The results for the execution time are as follows:
# Time_execuson
0.000228
0.000113
0.000199
0.000373
0.000767
0.000032
0.000070
0.000041
0.000037
Logically as the variable num_of_terms increases, the calculations also increase.
Why the execution time is not decreasing but decreasing?
Someone knows how to solve this problem?
Thank you.

回答 (2 件)

Philip Borghesani
Philip Borghesani 2019 年 1 月 11 日
編集済み: Philip Borghesani 2019 年 1 月 11 日
Matlab's JIT compiler performs different optimizations for code that runs multiple times and it may take many runs of a block of code before it is fully optimized. So even though later loops are doing more work they are better optimized . If you use a larger num_of_terms or repeate the experiment multiple times you should see your expected performance pattern.
Why is this a problem?
  1 件のコメント
John Blue
John Blue 2019 年 1 月 12 日
It was a problem if i used small matrix (adj) . Βecause with few repetitions (num_of_terms) I had the eigenvector with very good accuracy like the eigs().You are right what I need to increase num_of_terms the adj matrix and I have the pattern that I want.
Thank you.

サインインしてコメントする。


Adam
Adam 2019 年 1 月 11 日
doc timeit
is the best way to get simple timings from a piece of cide. It deals with running multiple times and averaging as well as eliminating the first time call overhead and other things like that.
When code is so fast though you should not expect the results to be very predictable in terms of how fast it is with respect to the inputs. It's just too fast to be that accurate.

カテゴリ

Help Center および File ExchangeJust for fun についてさらに検索

製品


リリース

R2017a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by