Soma
Soma

Reputation: 743

How can I calculate time of my main code?

I have a code which is included some functions. for every functions I use CPUTime. but in main model how can I calculate time. Please help me.

for example

using CPUTime
function Sminf2(ZB,ZT)
    model=CreateModel();
    WES=model[1];f1=model[2];f2=model[3];
    rf1=model[4];rf2=model[5];lf1=model[6];
    lf2=model[7];
    x=WES[:x];
    y=WES[:y];
   JuMP.setRHS(rf1,ZB[1]);
   JuMP.setRHS(lf1,ZT[1]);
   JuMP.setRHS(rf2,ZT[2]);
   JuMP.setRHS(lf2,ZB[2]);
   @objective(WES,Min,f2);
  status=solve(WES)
  return getvalue(x)
end
@time @CPUtime Sminf2(ZB,ZT)

-----------------------------------------------------------------

but in this main code how can I calculate the time?

using JuMP,CPLEX,CPUTime
include("WEIGHT.juliarc (2).jl");
include("CreateModel.juliarc.jl");
include("Sminf2.juliarc.jl");
include("Sminf1.juliarc.jl");
pq=[];
model=CreateModel();
WES=model[1];f1=model[2];f2=model[3];
rf1=model[4];rf2=model[5];lf1=model[6];
lf2=model[7];ofv1=model[8];ofv2=model[9];
x=WES[:x];
y=WES[:y];
for i=1:5
     W=WEIGHT(Zb,Zt);
     pq=[pq;W[1]];
end
println("PQ=",pq)

------------------------------------------------------------------------------

Upvotes: 0

Views: 370

Answers (1)

carstenbauer
carstenbauer

Reputation: 10127

Generally, it is recommended to use BenchmarkTools.jl for benchmarking a piece of code.

Paralleling the @time macro in Base Julia, BenchmarkTools exports the usually superior @btime macro, which, among other things, avoids measuring compilation time and performs a more precise statistical analysis. (see the package's documentation for details)

You can use it just as you use the @time macro, e.g. @btime rand(2,2)

To benchmark a block of code, such as your "main code", you could (and should) put that piece of code into a function or a begin ... end block. For example,

@btime begin
    # my code goes here
end

Note that, independent of benchmarking, it is anyways recommended to put performance critical code into functions, as is explained in the Performance Tips in Julia's documentation.

Having introduced @btime, of course, if the runtime of your code dominates over compilation time, as should probably be the case when benchmarking the whole code ("main code"), it's often nonetheless fine to use @time. It should be instructive to read this recent discourse thread where parts of how to use @time correctly have been discussed.

Upvotes: 3

Related Questions