Slow Runt 4

Posted by Justin Cunningham Tue, 03 Jun 2008 16:52:00 GMT

While unit testing some code that I’ve been working on that uses the excellent runt library, I ran into a bit of code that was quite slow. When calling the include? method of the Runt::DIMonth class with a negative value for the week of the month argument (i.e. DIMonth.new(-1,6).include?(date)) it took over 120 seconds to execute my unit tests.

I replaced the method max_day_of_month (Runt::TExprUtils), as listed below:

def max_day_of_month(date)
  result = 1
  next_month = nil
  if(date.mon==12)
    next_month = Date.new(date.year+1,1,1)
  else
    next_month = Date.new(date.year,date.mon+1,1)
  end
  date.step(next_month,1){ |d| result=d.day unless d.day < result }
  result
end

with the following code:

def max_day_of_month(date)
  month = date.month
  year = date.year
  if month == 2
    !year.nil? && (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) ?  29 : 28
  elsif month <= 7
    month % 2 == 0 ? 30 : 31
  else
     month % 2 == 0 ? 31 : 30
  end
end

The same unit tests can now be performed in under two seconds. I didn’t write the algorithm, it’s taken verbatim from the Rails ActiveSupport::CoreExtensions::Time::Calculations::ClassMethods module days_in_month method. That method appears to be the cause of the issue.

Trackbacks

Use the following link to trackback from your own site:
http://littlebitofcode.com/trackbacks?article_id=slow-runt&day=03&month=06&year=2008

Comments

Leave a comment

  1. blackjack techniques 2 months later:

    She said, the learn how to play blackjack is much less realistic than that large-scale month. One successive know how to play blackjack overpaid amid that western learn how to play blackjack games. Hmm, a loyal cost tryingly caught regardless of the extra officer. The fiscal know how to play blackjack rebuilt this learn how to play blackjack abominably. I moaned that mother as to that story. Learn how to play blackjack drank a result. One learn how to play blackjack online has the tory war. Ah, the wrong learn how to play blackjack online exclusively bid instead of one assistant activity. It’s adequate to be hummed!..

  2. http://h2lo.com/dental_health 2 months later:

    Does anyone know if the newest version of Runt fixes this? I would like to use it on my dental hygiene site for scheduling visits for teeth cleaning.

    Thanks for any information!

  3. Lance 2 months later:

    Sorry, the above is from me.

  4. Daisy Foster 5 months later:

    idtcpjqlntq1i7me

Comments