Julia如何进行性能测试,获取代码运行时间,类似于MATLAB的tic、toc
技术分享
发布于 2025-07-22 10:46:42
查看 1过去315天
在Julia中,可以使用如下方法进行性能测试,获取代码片段或者函数运行时间。
先准备好一份测试代码片段与函数
代码片段:
for i in 1:5
println("Testing $i")
sleep(1)
end
函数
function test()
for i in 1:5
println("Testing $i")
sleep(1)
end
end
1.@time
• 测试函数
@time test()
# 5.010443 seconds (85 allocations: 2.656 KiB)
• 测试代码片段
@time begin
for i in 1:5
println("Testing $i")
sleep(1)
end
end
# 5.010101 seconds (183 allocations: 9.234 KiB)
2.@elapsed 返回时间
• 测试函数
@elapsed test()
# 5.010462663
• 测试代码片段
@elapsed begin
for i in 1:5
println("Testing $i")
sleep(1)
end
end
# 5.009986319
3.@btime 会多次运行代码取平均值
• 测试函数
using BenchmarkTools
@btime test()
# 5.010 s (86 allocations: 2.95 KiB)
• 测试代码片段
using BenchmarkTools
@btime begin
for i in 1:5
println("Testing $i")
sleep(1)
end
end
# 5.010 s (86 allocations: 2.95 KiB)
所属专栏:Julia语言
产品信息:Syslab科学计算环境