Caching computation in rails?
Simple example: factorial modulus a large number
input: integer x
output: factorial( x ) % 12345678901234567
I want it so that if it computes factorial of N once, it will not have
to compute for N again.
code:
class SiteController < ApplicationController
caches_action :factorial, :inv
def examine
@inv = @params[''inv'']
@outv = factorial @inv.to_i
end
def factorial( inv )
y=1
while (inv > 0) do
y*=inv
inv-=1
end
(y % 12345678901234567)
end
end
I am running in production mode so caching should be enabled.
On Thu, 24 Mar 2005 15:28:56 -0500, Jesse Andrews <anotherjesse-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> Caching computation in rails? > > Simple example: factorial modulus a large number > input: integer x > output: factorial( x ) % 12345678901234567 > > I want it so that if it computes factorial of N once, it will not have > to compute for N again. > > code: > > class SiteController < ApplicationController > caches_action :factorial, :inv > > def examine > @inv = @params[''inv''] > @outv = factorial @inv.to_i > end > > def factorial( inv ) > y=1 > while (inv > 0) do > y*=inv > inv-=1 > end > (y % 12345678901234567) > end > > end >Store the result in a hash in the session?
> Store the result in a hash in the session?Why in a session? There is no reason to recompute it for each user. You can just keep it in memory. If you need to recompute it every say ... 10 minutes (doesn''t make any sense for the sample, i know) you can use something like typo''s simplecache which is basically a hash with Alzheimer''s: http://typo.leetsoft.com/trac.cgi/file/trunk/app/models/simple_cache.rb -- Tobi http://www.snowdevil.ca - Snowboards that don''t suck http://www.hieraki.org - Open source book authoring http://blog.leetsoft.com - Technical weblog
On Thu, 24 Mar 2005 23:59:59 -0500, Tobias Luetke <tobias.luetke-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> > Store the result in a hash in the session? > > Why in a session? There is no reason to recompute it for each user. > You can just keep it in memory. > > If you need to recompute it every say ... 10 minutes (doesn''t make any > sense for the sample, i know) you can use something like typo''s > simplecache which is basically a hash with Alzheimer''s: > > http://typo.leetsoft.com/trac.cgi/file/trunk/app/models/simple_cache.rbThat''s pretty slick. I was looking for a way to cache application data. This looks like it''ll work nicely. -- rick http://techno-weenie.net