Question

I'm using celluloid's every method to execute a block every microsecond however it seems to always call the block every second even when I specify a decimal.

interval = 1.0 / 2.0

every interval do
  puts "*"*80
  puts "Time: #{Time.now}"
  puts "*"*80
end

I would expect this to be called every 0.5 seconds. But it is called every one second.

Any suggestions?

Was it helpful?

Solution

You can get fractional second resolution with Celluloid.

Celluloid uses the Timers gem to manage the every, which does good floating point time math and ruby's sleep which has reasonable sub-second resolution.

The following code works perfectly:

class Bob
  include Celluloid
  def fred
    every 0.5 do
      puts Time.now.strftime "%M:%S.%N"
    end
  end
end

Bob.new.fred

And it produces the following output:

22:51.299923000
22:51.801311000
22:52.302229000
22:52.803512000
22:53.304800000
22:53.805759000
22:54.307003000
22:54.808279000
22:55.309358000
22:55.810017000

As you can see, it is not perfect, but close enough for most purposes.

If you are seeing different results, it is likely because of how long your code takes in the block you have given to every or other timers running and starving that particular one. I would approach it by simplifying the situation as much as possible and slowly adding parts back in to determine where the slowdown is occurring.

As for microsecond resolution, I don't think you can hope to get that far down reliably with any non-trivial code.

The trivial example:

def bob
  puts Time.now.strftime "%M:%S.%N"
  sleep 1.0e-6
  puts Time.now.strftime "%M:%S.%N"
end

Produces:

31:07.373858000
31:07.373936000


31:08.430110000
31:08.430183000


31:09.062000000
31:09.062079000


31:09.638078000
31:09.638156000

So as you can see, even just a base ruby version on my machine running nothing but a simple IO line doesn't reliably give me microsecond speeds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top