gpt4 book ai didi

macros - 包装 TimerOutputs 宏

转载 作者:行者123 更新时间:2023-12-05 04:34:44 25 4
gpt4 key购买 nike

我有一个情况,有一个变量会很方便,to , 可以是 TimerOutputnothing .我有兴趣提供一个采用与 @timeit 相同参数的宏来自 TimerOutputs(例如 @timeit to "time spent" s = foo() )。因为to可能设置为 nothing ,我不能简单地禁用 TimerObject。

如果to已设置,我的偏好是将参数传递给 @timeit , 但可以忍受调用 timer_expr(__module__, false, args...) .

如果to未设置,我只想将剩余的参数(可能类似于 args[3:end])作为表达式返回。

我已经为此烦恼了一天左右,并且可以单独处理每个案例。对于我不涉及 TimerOutput 的情况,这似乎可行:

macro no_timer(args...)
args[3:end][1]
end

对于我使用 TimerOutput 的情况,我可以这样做:

macro with_timer(args...)
timer_expr(__module__, false, args...)
end

这并不奇怪,因为这就是 @timeit

我还没有想出如何在一个宏中处理这两种情况。我通过将所有内容包装在三元运算符中得到了最接近的 - 即 return :(isnothing($(args[1])) ? <expression stuff> : <TimerOutput stuff>) ,但存在某种程度的抽象不匹配,我还没有解释清楚。

附录:我得出的结论是我的原始框架是一个“X-Y”问题。我实际上并不需要一个新的宏来解决我的问题 - 因此我接受了我所做的答案。也就是说,令我震惊的是,所提供的两个答案都远离定义宏。

最佳答案

您已经在 TimerOuputs 中拥有此功能。只需使用 disable_timer!enable_timer! 方法。

julia> const to = TimerOutput();

julia> disable_timer!(to);

julia> @timeit to "sleep" sleep(0.02)

julia> to
────────────────────────────────────────────────────────────────────
Time Allocations
─────────────────────── ────────────────────────
Tot / % measured: 23.6s / 0.0% 464KiB / 0.0%

Section ncalls time %tot avg alloc %tot avg
────────────────────────────────────────────────────────────────────
────────────────────────────────────────────────────────────────────

julia> enable_timer!(to);


julia> @timeit to "sleep" sleep(0.02)

julia> to
────────────────────────────────────────────────────────────────────
Time Allocations
─────────────────────── ────────────────────────
Tot / % measured: 37.3s / 0.1% 777KiB / 0.0%

Section ncalls time %tot avg alloc %tot avg
────────────────────────────────────────────────────────────────────
sleep 1 22.6ms 100.0% 22.6ms 320B 100.0% 320B
────────────────────────────────────────────────────────────────────

关于macros - 包装 TimerOutputs 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71161611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com