高精度睡眠在Ruby中

Joh*_*yer 0 ruby precision sleep timer

可能重复:
Ruby睡眠或延迟不到一秒钟?

我有100-1000个线程正在运行(或更多).这些线程中的每一个都应该在完全相同的时刻执行特定的方法(尽可能最精确).

我能想到的唯一解决方案就是让每个线程都按照某个时间戳的差异进行休眠,但这sleep()并不准确.我也在考虑使用EventMachineEventMachine::Timer不是,但这似乎更不可靠和准确.

您将使用什么技术来获得最佳效果?

the*_*Man 5

很多人都不知道它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)

运行的其他任务可能会使更多的偏差.

  • 我不确定Ruby是否能够提供所需的精确度,至少是MRI及其当前状态.*也许*带有Java基础的JRuby可以做得更好一点,但1000个线程或进程,在同一时刻触发似乎是一个陡峭的请求,即使在C中,尤其是像我们大多数人现在使用的商品硬件. (2认同)