0

I'm trying to write a function that will return the number of days between two dates as quickly as possible. This function gets called thousands ofa million times in my code and optimizing it to the max would be really helpful. The dates are strings in the format yyyy-mm-dd.

Here's the best I have so far:

protected function daysBetween($date1, $date2)
{
  list($year1,$month1,$day1) = explode('-',$date1);
  list($year2,$month2,$day2) = explode('-',$date2);
  return (int)abs((mktime(0,0,0,$month1,$day1,$year1) -
                   mktime(0,0,0,$month2,$day2,$year2)) / 86400);
}

How can I make this execute in the shortest amount of time possible?

Alex Grin
  • 8,121
  • 6
  • 33
  • 57
  • But is it a duplicate? The other question compares datetime to date, and isn't concerned with efficiency. This one is concerned ONLY with efficiency, as the author clearly already has a solution to get the date delta. Anyway lyoshenka, I can't think of a better way. mktime is almost surely way faster than strtotime, and solutions not using mktime would probably also be slower. I think you got it. – Kasapo Oct 06 '11 at 21:45
  • @AurelioDeRosa This question is different. The one you link to just wants to know _how_ to do it, however this one wants to know how to do it _in the fastest way possible_. – Bojangles Oct 06 '11 at 21:46
  • Did you look at http://www.php.net/manual/en/datetime.diff.php ? One would hope that would be more efficient... – Aerik Oct 06 '11 at 22:04

1 Answers1

1

Changing mktime() to gmmktime() reduces the time taken by over 50% for me. That's the single greatest improvement* that I can see.

* I didn't look very hard. SO doesn't seem the right place for tweaking your function, for your script, for your hardware, for your individual needs, especially since it's only called thousands of times.

salathe
  • 51,324
  • 12
  • 104
  • 132
  • Thanks, that worked really well. When I said "a thousand times", I really meant "a million times". I hadn't really profiled the code at the time, but I knew that that was the culprit. – Alex Grin Oct 07 '11 at 14:02
  • In retrospect, this is very surprising. The php manual page for gmmktime says that it uses mktime internally. So it seems impossible that gmmktime would be faster than mktime. But it definitely is for me (and for you). I wonder how that can be... – Alex Grin Oct 17 '11 at 22:54