I am writing a C extension for Ruby, which needs to heavily use time objects. The performance is critical for this application. How should I go about creating Time objects from C API for maximum performance? I did not find anything relevant in ruby.h include file.
Asked
Active
Viewed 147 times
3
-
1It takes 1 microsecond per call to `Time.new` from Ruby, as timed on my laptop in IRB. Which means you can realistically create 1,000,000 `Time` objects per second. Just how many do you want to create, and is it really the instantiation of these objects which will be your performance challenge? – Neil Slater Jun 09 '13 at 19:52
-
Right, I am going to process a few hundred millions of such objects. A few minutes is acceptable time for me, however I have the time record in C and I thought of any shortcut to create a Ruby Time object from it (similar to e.g. rb_struct_new for Structs). – Piotr Turek Jun 09 '13 at 20:08
-
If possible, write it in Ruby first and get it working, and benchmark it to see if the performance is acceptable. If not, then go the hard route of writing it in C. – Andrew Marshall Jun 09 '13 at 20:13
-
I have done it already and pure Ruby implementation is not fast enough. The desired API (and tests) involves exposing Ruby Time objects. – Piotr Turek Jun 09 '13 at 20:25
1 Answers
2
I've always just used rb_time_new
- it takes a time_t
and a second parameter with the fractional part of the time, in microseconds.
Depending on what you are doing it might make sense to only store the time_t
(and do your calculations on those) and lazily convert to ruby Time objects only when you have to

Frederick Cheung
- 83,189
- 8
- 152
- 174
-
Relevant code for reference: https://github.com/ruby/ruby/blob/trunk/time.c#L2272 – Casper Jun 09 '13 at 20:34
-
It is significantly faster than calling via the full Ruby constructor e.g. `rb_funcall( cTime, id_new_method, 0 );` I would say the time to create "a few hundred million" is measured in seconds, although they still have to be put somewhere! – Neil Slater Jun 09 '13 at 20:49
-
I missed it somehow, but it is exactly what I was looking for, thanks! – Piotr Turek Jun 09 '13 at 20:57