如何禁止Julia BenchmarkTools @time向终端打印结果并存变量
Julia 禁用计时宏自动打印、自定义输出格式方法
针对 Julia 自带的@time宏
Julia 标准库提供了两个不会自动打印统计信息的计时宏,可以直接把结果存入变量:
@elapsed 表达式:仅返回表达式执行的总耗时,单位为秒,无任何终端输出@timed 表达式:返回包含所有统计信息的元组,顺序为(表达式返回值, 执行秒数, 总分配字节数, GC耗时秒数, 编译耗时, 重编译次数...),无任何终端输出
使用示例:
# 第一次直接运行函数做预热,消除编译开销,不需要计时 main() # 第二次正式运行,只取耗时 cost_seconds = @elapsed main() # 如果需要同时获取内存、GC等其他统计数据,用@timed res, cost_seconds, alloc_bytes, gc_cost, compile_cost... = @timed main()
针对 BenchmarkTools 提供的计时工具
BenchmarkTools 里自动打印统计信息的是@btime宏,如果你用@benchmark宏,它会直接返回BenchmarkTools.Trial类型的结果对象,不会自动向终端打印任何内容,你可以按需从对象里取需要的统计字段:
using BenchmarkTools # 预热 main() # 跑基准测试,结果存入变量 trial = @benchmark main() # 按需取值:times字段单位为纳秒,除以1e9转成秒 median_cost = median(trial.times) / 1e9 total_alloc = trial.memory # 总分配内存,单位字节 alloc_count = trial.allocs # 分配次数
自定义输出实现示例
替换你代码末尾的两次@time块和打印逻辑即可:
# 预热消除编译开销 main() # 正式计时 elapsed_ms = round(@elapsed(main()) * 1000, digits=0) println("Solution: ", solution) println("\n\nProgram completed in ", elapsed_ms, " milliseconds.")
运行后就只会输出你期望的格式,不会带多余的计时统计行。
内容的提问来源于stack exchange,提问作者MFerguson
相关产品推荐
相关产品推荐

