执行时间与测量

Julia 中级

Anthony Markham

Quantitative Developer

初始函数定义

  • 问题可有多解,但常有"最优"解
  • 大内存占用与长执行时间会让用户和开发者沮丧
  • 循环常导致更长的执行时间与低效
function my_function()
  x = Vector{Char}()
  for i in "Anthony"
    push!(x, i)
  end
  println(x)
end
['A', 'n', 't', 'h', 'o', 'n', 'y']
Julia 中级

基础 @time 宏

  • 我们用宏来计时函数。

优点:

  • Julia 基础包自带
  • 简单易用
  • 输出易于理解

缺点:

  • 灵活性有限
  • 只计时一次
  • 首次调用有编译开销
  • 在函数上调用宏
@time my_function()
@time my_function()
  • 返回值

0.278266 seconds (110.66 k allocations: 6.343 MiB, 99.79% compilation time)

0.000493 seconds (100 allocations: 3.281 KiB)

Julia 中级

BenchmarkTools - @benchmark

为何用 @benchmark 而非 @time

  • 最灵活,可调参数多,如 samples 数量。
  • 提供深入的运行统计(范围、中位数、均值)。
@benchmark my_function

Julia 中级

Passons à la pratique !

Julia 中级

Preparing Video For Download...