From: brabuhr@... Date: 2010-06-08T04:12:14+09:00 Subject: Re: A better way to write this function? On Wed, Jun 2, 2010 at 11:44 PM, Colin Bartlett wrote: > On Fri, May 28, 2010 at 4:20 PM, Jason Lillywhite < > jason.lillywhite@gmail.com> wrote: > >> Here is my attempt at Newton's second law in Ruby: >>   ... >> What if I needed more speed but still wanted it in Ruby? >> > > Using C for the "fast" bits has been suggested. > > As an alternative to C for speed, I've found that using JRuby with parts of > the code as Java functions works well. I took a quick shot w/ duby-inline. Host: 2.6.32-22-generic #33-Ubuntu SMP Wed Apr 28 13:27:30 UTC 2010 i686 GNU/Linux Intel(R) Pentium(R) M processor 1.60GHz Benchmark block: 100000.times{ velocity(0.5, 21.6, 600, 10, 0.0) } "Original" code (see note below): ruby 1.8.7 (2010-01-10 patchlevel 249) [i486-linux] user system total real 18.210000 0.040000 18.250000 ( 21.596111) jruby 1.5.0 (ruby 1.8.7 patchlevel 249) (2010-05-12 6769999) (OpenJDK Client VM 1.6.0_18) [i386-java] user system total real 4.525000 0.000000 4.525000 ( 4.525000) jruby 1.5.0 (ruby 1.8.7 patchlevel 249) (2010-05-12 6769999) (OpenJDK Server VM 1.6.0_18) [i386-java] user system total real 3.651000 0.000000 3.651000 ( 3.651000) Duby code: jruby 1.5.0 (ruby 1.8.7 patchlevel 249) (2010-05-12 6769999) (OpenJDK Client VM 1.6.0_18) [i386-java] 0.415000 0.000000 0.415000 ( 0.415000) jruby 1.5.0 (ruby 1.8.7 patchlevel 249) (2010-05-12 6769999) (OpenJDK Server VM 1.6.0_18) [i386-java] 0.208000 0.000000 0.208000 ( 0.208000) I had to cheat a little bit and removed the array and the block to make it Duby-compatible: G = 9.8 class Newton def rb_velocity(c, m, t, dt, vi) t += dt steps = t/dt i = 0 while i < steps v = vi vi = v + ( G - c/m*v) * dt i += 1 end vi end end And, the duby version: require 'inline' require 'duby_inline' G = 9.8 class Newton inline :Duby do |builder| builder.duby " def db_velocity(c:double, m:double, t:int, dt:int, vi:double) t += dt steps = t/dt i = 0 while i < steps v = vi vi = v + ( #{G} - c/m*v) * dt i += 1 end vi end " end end