【问题标题】:timeout function in JuliaJulia 中的超时函数
【发布时间】:2018-07-10 11:51:50
【问题描述】:

我在 Julia 中寻找超时功能。我的问题如下:我正在生成要在我的函数中测试的随机字符串。问题是某些输入会导致无限的运行时间。所以我想为每次运行设置一个最大运行时间。 我的函数只需要 1 个参数:一个字符串。 欢迎任何帮助! TIA, 妮可

【问题讨论】:

    标签: timeout julia


    【解决方案1】:

    我不确定是否有没有与您正在调用的函数合作的好方法(可能缺少使用多个线程)。你可以使用Timer:

    julia> function repeat_forever(timer = Timer(1.0))
           while true
               isopen(timer) || break
               yield()
           end
           return "timer finished!"
       end
    repeat_forever (generic function with 2 methods)
    
    julia> @time repeat_forever(Timer(0.25))   # first call will be off due to compilation
      0.254629 seconds (484.42 k allocations: 7.454 MiB)
    "timer finished!"
    
    julia> @time repeat_forever(Timer(0.25))
      0.250661 seconds (484.81 k allocations: 7.398 MiB, 1.30% gc time)
    "timer finished!"
    
    julia> @time repeat_forever(Timer(1.25))
      1.250994 seconds (2.51 M allocations: 38.329 MiB, 0.27% gc time)
    "timer finished!"
    

    循环中的yield 调用是必要的,这样计时器任务本身才能运行。

    【讨论】:

      猜你喜欢
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      相关资源
      最近更新 更多