如何在有限的时间内运行代码?

时间:2019-10-13 06:34:57

标签: julia

是否可以在一定时间间隔内运行代码?例如,有一个小功能如下:

   function test(n)
     A = rand(n, n)
     b = rand(n)
   end

如何将测试代码运行5秒钟然后将其停止?

你能帮我吗? 非常感谢。

1 个答案:

答案 0 :(得分:2)

这是您可以做的:


function test(n)
     A = rand(n, n)
     b = rand(n)
end

start_time = time_ns() #Gets current time in nano seconds
seconds = 5000000000 #converted 5 seconds to nano seconds. 

@time begin
    while time_ns() - start_time <= seconds:  
        test(1)
    end

end
#Note this code is designed to provide the logic of implementing this idea and may or may not work in your case. 

我在评论中提到的最困难的部分是编程中所有基于时间的事情都是尽力而为的情况,而不是绝对的情况。

See some examples from the docs about time供参考或下面的示例:

julia> @time begin
           sleep(0.3)
       end
  0.305428 seconds (9 allocations: 352 bytes)

julia> 

即使我们说过我们想睡0.3秒,但它的睡眠时间却约为0.305秒。希望可以通过尝试这样做来阐明问题。

根据使用线程的方式,这也是可能的。如果只想给一个函数5秒钟来返回一个新值,则可以使用线程调用该函数,然后检查接受该返回值的变量以查看其是否已更新。如果还不到5秒,您可以杀死线程或继续前进。虽然,我对此不是100%肯定。