Background
我自学了机器学习,最近开始深入研究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
如何使用适当的库比较在 Julia 中执行相同任务的函数的执行时间(在本例中为JuliaImages
(。
朱莉娅是否为时间/基准提供任何函数/宏?
using BenchmarkTools
是推荐的对Julia函数进行基准测试的方法。除非您要计时需要相当长的时间,否则请使用@benchmark
或从中导出的不太冗长的@btime
宏。 由于这些宏背后的机制会多次评估目标函数,因此@time
对于对运行缓慢的事情进行基准测试(例如,涉及磁盘访问或非常耗时的计算(非常有用。
正确使用@btime
或@benchmark
很重要,这样可以避免误导性结果。通常,您正在对接受一个或多个参数的函数进行基准测试。基准测试时,所有参数都应该是外部变量:(没有基准测试宏(
x = 1
f(x)
# do not use f(1)
该函数将被多次计算。为了防止在计算函数时重新计算函数参数,我们必须通过在用作参数的每个变量的名称前面加上一个$
来标记每个参数。 基准测试宏使用它来指示应在基准测试过程开始时对变量进行一次计算(解析(,然后直接按原样重用结果:
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
虽然有一些参数可以调整,但默认值通常效果很好。有关适用于经验丰富的 ursers 的 BenchmarkTools 的更多信息,请参阅手册。
> Julia 提供了两个用于计时/基准测试代码运行时的宏。这些是:
- @time
- @benchmark:外部,按
Pkg.add("BenchmarkTools")
安装
使用BenchmarkTools的@benchmark非常简单,并且有助于您比较两种语言的速度。 对你提供的 python bench 使用@benchark
的示例。
using Images, FileIO, BenchmarkTools
@benchmark img = load("sample_image.png")
输出:
BenchmarkTools.Trial:
memory estimate: 3.39 MiB
allocs estimate: 322
--------------
minimum time: 76.631 ms (0.00% GC)
median time: 105.579 ms (0.00% GC)
mean time: 110.319 ms (0.41% GC)
maximum time: 209.470 ms (0.00% GC)
--------------
samples: 46
evals/sample: 1
现在为了比较平均时间,您应该将samples
(46( 作为 python timeit 代码中的数字,并将其除以相同的数字以获得平均执行时间。
print(str(round((timeit.timeit(stmt = s, setup = setup, number = 46)/46)*1000, 2)) + " ms")
您可以按照此过程对Julia和Python中的任何函数进行基准测试。 我希望你的怀疑已经清除。
注意:从统计的角度来看,@benchmark比@time要好得多。