Julia:从代码中访问@time 计时和内存分配值

Julia: access @time timing and memory allocation values from within code

我正在分析我的 Julia 应用程序,特别是函数调用的执行时间和内存分配。我想自动将此信息存储到数据库中,这样就可以 运行 无需监督。

我要存储的信息是@time返回的信息,形式为:

@time some_function()
 86.278909 seconds (6.94 M allocations: 383.520 MB, 0.08% gc time)

是否可以从代码本身访问此信息,而不是仅仅打印出来?

我知道我可以使用 tic()toq() 访问时间组件,但是内存分配呢?

首先,Julia 允许很好地访问所有内容的内部结构。因此,如果某事做了某事,只需看看内部是如何做的。在 @time 宏的情况下,在 REPL 中使用 macroexpand 来查看内部:

macroexpand(:(@time some_function()))

这样做之后,tic()toq() 的分配等价物是 before = Base.gc_numdiff = Base.GC_Diff(Base.gc_num(),before)

diff 变量现在包含分配统计信息。

Base.gc_alloc_count(diff) 例如给出分配计数。

干杯!

有一个 @timed 宏可以为您提供所有这些信息:

julia> @timed sleep(1)
(nothing,1.00417,624,0.0,Base.GC_Diff(624,0,0,13,0,0,0,0,0))

help?> @timed
  @timed

  A macro to execute an expression, and return the value of the expression, elapsed
  time, total bytes allocated, garbage collection time, and an object with various
  memory allocation counters.