Joh*_*yer 0 ruby precision sleep timer
可能重复:
Ruby睡眠或延迟不到一秒钟?
我有100-1000个线程正在运行(或更多).这些线程中的每一个都应该在完全相同的时刻执行特定的方法(尽可能最精确).
我能想到的唯一解决方案就是让每个线程都按照某个时间戳的差异进行休眠,但这sleep()并不准确.我也在考虑使用EventMachine而EventMachine::Timer不是,但这似乎更不可靠和准确.
您将使用什么技术来获得最佳效果?
很多人都不知道它sleep具有浮动值:
Suspends the current thread for duration seconds (which may be
any number, including a Float with fractional seconds). Returns the actual
number of seconds slept (rounded), which may be less than that asked for if
another thread calls Thread#run. Called without an argument, sleep() will
sleep forever.
Time.new #=> 2008-03-08 19:56:19 +0900
sleep 1.2 #=> 1
Time.new #=> 2008-03-08 19:56:20 +0900
sleep 1.9 #=> 2
Time.new #=> 2008-03-08 19:56:22 +0900
Run Code Online (Sandbox Code Playgroud)
无法保证延迟是准确的:
3.times do
t1 = Time.now.to_f
sleep 0.5
t2 = Time.now.to_f
puts t2 - t1
end
Run Code Online (Sandbox Code Playgroud)
结果是:
0.501162052154541
0.5010881423950195
0.5001001358032227
Run Code Online (Sandbox Code Playgroud)
运行的其他任务可能会使更多的偏差.
| 归档时间: |
|
| 查看次数: |
4025 次 |
| 最近记录: |