首页 > 解决方案 > 如何测量 Julia 中一小部分代码的内存使用情况?

问题描述

我想知道,如何通过一小部分代码来测量内存使用情况?假设我有 50 行代码,我只取三行(随机)并找到它们正在使用的内存。

在 python 中,可以使用这样的语法来衡量使用情况:

**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**

我尝试过使用begin - end循环,但首先,我不确定它是否是好方法,其次,我可以知道如何使用 package.json 提取内存使用情况benchmarktools

朱莉娅:

using BenchmarkTools

**code**

@btime begin
   ** code **
end

**code**

我怎样才能以这种方式提取信息?

期待建议!

谢谢!!

标签: memory-managementjulia

解决方案


我想一种解决方法是将要进行基准测试的代码放入一个函数并对该函数进行基准测试:

using BenchmarkTools

# code before

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

# code after

要保存您的基准,您可能需要使用@benchmark而不是@btime,例如:

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

推荐阅读