views:

167

answers:

4

I have a fairly intensive algorithm that must be run pretty often (many times per second) in my RoR application. Considering how slow Ruby is with this kind of stuff, I don't think it would be good to do the work in Ruby.

You may be thinking I should add it to a work queue of some sort and have a C++ app work it down, but I need the result returned instantly. Is there a way to extend RoR with a C++ plugin or something? What if I something like connecting to the C++ app via a socket? Or would that just be crazy?

+8  A: 

[...] I don't think [...]

Make the measurement.

That is, if it's reasonably simple to write in Ruby, implement it in ruby first and measure. Then, if it really is too slow, find out how to get around it.

Even if you need to rewrite the algorithm in another language, you have an algorithm in ruby you basically just have to copy, so it won't be as time-consuming as writing it in (say) C++ the first time.

But measure it first.

Jonas Kölker
I understand what you're saying, but I'm asking more of HOW I would go about implementing it in another language if I needed to.
ryeguy
This is crucial advice. Sorry but one should always ask "should I?" before one asks "how can I?", especially since using rubyline would actually make it *harder* to change the algorithm itself once you are done.
Joe Soul-bringer
+6  A: 

Several possibilities.

First, see if you can move to Ruby 1.9: it's dramatically faster than 1.8.

Second, there is indeed a way to write Ruby extensions in C.

Third, you could indeed write a separate process in any language you find convenient and use it. The best approach is hard to guess, since you don't really give much detail, but think about how popen works.

Charlie Martin
+1  A: 

Another possibility (if your setup allows) is to use JRuby. Then you can implement the algorithm in Java.

PEZ
+6  A: 

Another alternative is RubyInline which allows you to write C/C++ code within your Ruby code. This fits in nicely with Jonas Kölker's suggestion to write the algorithm in Ruby first and then find the bottlenecks. You can then use RubyInline to optimize the bottlenecks.

floehopper
Didn't know about that. It looks awesome. +1
DanSingerman
See "Using RubyInline for Optimization" by Eric Hodel for an example: http://segment7.net/projects/ruby/inline_optimization.html
floehopper