julia - 我可以通过哪些方式对 Julia 函数进行基准测试?
问题描述
背景
我自学了机器学习,最近开始研究 Julia 机器学习生态系统。
来自 python 背景并具有一些 Tensorflow 和OpenCV /
skimage
经验,我想将 Julia ML 库(Flux/JuliaImages)与它的同行进行基准测试,看看它真正执行 CV(任何)任务的速度有多快或多慢,并决定是否我应该转向使用 Julia。
我知道如何使用timeit
这样的模块在 python 中执行一个函数所花费的时间:
#Loading an Image using OpenCV
s = """\
img = cv2.imread('sample_image.png', 1)
"""
setup = """\
import timeit
"""
print(str(round((timeit.timeit(stmt = s, setup = setup, number = 1))*1000, 2)) + " ms")
#printing the time taken in ms rounded to 2 digits
如何使用适当的库(在本例中为JuliaImages
)比较在 Julia 中执行相同任务的函数的执行时间。
Julia 是否为 time/benchmark 提供任何函数/宏?
解决方案
using BenchmarkTools
是对 Julia 函数进行基准测试的推荐方法。除非您正在计时一些需要很长时间的事情,否则请使用其中一个或从它导出@benchmark
的不太冗长的宏。@btime
因为这些宏背后的机制多次评估目标函数,@time
所以对于运行缓慢的事物(例如涉及磁盘访问或非常耗时的计算)进行基准测试很有用。
@btime
使用或正确使用很重要@benchmark
,这样可以避免误导性结果。通常,您正在对一个接受一个或多个参数的函数进行基准测试。基准测试时,所有参数都应该是外部变量:(没有基准宏)
x = 1
f(x)
# do not use f(1)
该函数将被多次评估。为了防止在每次评估函数时重新评估函数参数,我们必须通过在$
用作参数的每个变量的名称前加上前缀 a 来标记每个参数。基准测试宏使用它来指示应该在基准测试过程开始时评估(解析)一次变量,然后直接重用结果:
julia> using BenchmarkTools
julia> a = 1/2;
julia> b = 1/4;
julia> c = 1/8;
julia> a, b, c
(0.5, 0.25, 0.125)
julia> function sum_cosines(x, y, z)
return cos(x) + cos(y) + cos(z)
end;
julia> @btime sum_cosines($a, $b, $c); # the `;` suppresses printing the returned value
11.899 ns (0 allocations: 0 bytes) # calling the function takes ~12 ns (nanoseconds)
# the function does not allocate any memory
# if we omit the '$', what we see is misleading
julia> @btime sum_cosines(a, b, c); # the function appears more than twice slower
28.441 ns (1 allocation: 16 bytes) # the function appears to be allocating memory
# @benchmark can be used the same way that @btime is used
julia> @benchmark sum_cosines($a,$b,$c) # do not use a ';' here
BenchmarkTools.Trial:
memory estimate: 0 bytes
allocs estimate: 0
--------------
minimum time: 12.111 ns (0.00% GC)
median time: 12.213 ns (0.00% GC)
mean time: 12.500 ns (0.00% GC)
maximum time: 39.741 ns (0.00% GC)
--------------
samples: 1500
evals/sample: 999
虽然有一些参数可以调整,但默认值通常效果很好。有关面向经验丰富的用户的 BenchmarkTools 的更多信息,请参阅手册。
推荐阅读
- wordpress - 隐藏 WordPress 中的数据库错误
- python - 无法获得所需的部分,将其余部分踢出
- xquery - 如何在osb中测试一系列转换
- apache-spark - 如何覆盖 HIVE 中的多个分区
- javascript - 在鼠标悬停时获取正确的 x 和 y 坐标
- r - 用先前的非缺失值填充列,没有 ID
- windows - 打包为 IExpress 可执行文件的批处理文件无法正常运行
- php - 如何详细说明工匠命令?-- 总是让 PDO 连接被拒绝
- c++ - 如何让函数返回一个数组?用于使 DLL 在 VB.NET 中使用
- python - 如何访问 python LogRecord 的 asctime?