<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>Moves On Rails: Tag C</title>
    <link>http://www.movesonrails.com/articles/tag/c?tag=c</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>New ways to look at software</description>
    <item>
      <title>Optimizing math</title>
      <description>&lt;p&gt;As you might have guessed from Bart's previous article we've been looking at ways to speed up our Rails app. We've been profiling and query optimizing but at some point we reached a dead end.&lt;/p&gt;

&lt;p&gt;Our app needs to calculate a lot of distances between geo locations. Until now we've been happy using a home-grown Ruby method to calculate these distances but our profiling showed that it was (as one may suspect) horribly slow.&lt;/p&gt;

&lt;p&gt;We now have several options:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;We could try to built a faster Ruby method (but that would be hard since it's pure math and not really a lot can be done here)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We could use the database (mysql in our case) to calculate our distances (A lot more db connections in our case, since we need distances between lots of points. Not the standard stuff that gems like acts_as_mappable can handle)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use RubyInline to create a faster C based method&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We decided to look at RubyInline. A gem that enabled C code to be used right inside a Ruby script. We rewrote the method in C. A simple benchmark proved that our inline C method was 2.3 times faster!&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;pre&gt;
require 'inline'
inline do |builder|
    builder.include '&amp;lt;math.h&amp;gt;'
    builder.c "double calc_distance_between(...) { ... }"
end
&lt;/pre&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Although this result is very good, it does complicate your app and makes it less readable. These inline methods have to be used with care. But in our simple (and very localized) case we decided to keep the C method in favor of the pure Ruby call.&lt;/p&gt;</description>
      <pubDate>Thu, 10 Apr 2008 22:43:00 +0200</pubDate>
      <guid isPermaLink="false">urn:uuid:341a43a2-ff84-429a-b541-ca10ccb44f5d</guid>
      <author>andre.foeken@movesonrails.com (Andre Foeken)</author>
      <link>http://www.movesonrails.com/articles/2008/04/10/optimizing-math</link>
      <category>Rails</category>
      <category>Ruby</category>
      <category>rubyinline</category>
      <category>C</category>
      <category>math</category>
      <category>profile</category>
      <category>speed</category>
      <category>distance</category>
    </item>
  </channel>
</rss>
