Mohammad Saad
Mohammad Saad

Reputation: 2005

How to measure the memory usage for a small part of your code in Julia?

I would like to know, how can I measure the memory usage by a small part of my code? Lets say I have 50 lines of code, where I take only three lines (randomly) and find the memory being used by them.

In python, one can use such syntax to measure the usage:

**code**

psutil.virtual_memory().total -psutil.virtual_memory().available)/1048/1048/1048 

**code**

psutil.virtual_memory().total -psutil.virtual_memory().available)/1048/1048/1048 

**code**

I have tried using begin - end loop but firstly, I am not sure whether it is good approach and secondly, may i know how can i extract just the memory usage using benchmarktools package.

Julia:

using BenchmarkTools

**code**

@btime begin
   ** code **
end

**code**

How may I extract the information in such a manner?

Look forward to the suggestions!

Thanks!!

Upvotes: 3

Views: 598

Answers (1)

Benoit Pasquier
Benoit Pasquier

Reputation: 3015

I guess one workaround would be to put the code you want to benchmark into a function and benchmark that function:

using BenchmarkTools

# code before

f() = # code to benchmark
@btime f() ;

# code after

To save your benchmarks you probably need to use @benchmark instead of @btime, as in, e.g.:

julia> t = @benchmark x = [sin(3.0)]
BenchmarkTools.Trial:
  memory estimate:  96 bytes
  allocs estimate:  1
  --------------
  minimum time:     26.594 ns (0.00% GC)
  median time:      29.141 ns (0.00% GC)
  mean time:        33.709 ns (5.34% GC)
  maximum time:     1.709 μs (97.96% GC)
  --------------
  samples:          10000
  evals/sample:     992

julia> t.allocs
1

julia> t.memory
96

julia> t.times
10000-element Vector{Float64}:
   26.59375
   26.616935483870968
   26.617943548387096
   26.66532258064516
   26.691532258064516
    ⋮
 1032.6875
 1043.6219758064517
 1242.3336693548388
 1708.797379032258

Upvotes: 3

Related Questions