Which means that in the course of a given second, he's spending a lot of time formatting several java Date objects that result in the same string. So to reduce the amount of wasted time, he created a little wrapper class for his formater, which cached the last Date and formatted String, and if no more then a second had elapsed the next time it was called, he just reused the cached String.
Major speed improvement.
Which lead me to wonder about the same performance issue in perl. Perl times are only precise down to the second, but what if you are only formating dates down to the minute? Here's what I Benchmarked, as you can see, I used a really high numer of iterations, to make sure it lasted enough wallclock seconds to be a worthwhile test. It should also be clear that for applications that expect to do a lot of time formatting at a high frequency, it's worth it to cache the string.
(I'll leave it as an excercise for the reader to determine if there's any significant performance downside in applications where you don't format times at a high frequency)
use Benchmark qw(cmpthese countit); use POSIX qw(strftime); use constant TIME => 10000000; use constant FORMAT => '%Y-%m-%d %H:%M'; my $trash; sub plain_strftime { return strftime(FORMAT, localtime(shift)); } my ($timecache, $strcache) = (0, &plain_strftime($timecache)); sub cache_strftime { my $t = shift; if ($t - $timecache > 60) { $timecache = $t; $strcache = &plain_strftime($timecache); } return $strcache; } cmpthese(TIME, { 'plain' => sub { $trash = &plain_strftime(time); }, 'cache' => sub { $trash = &cache_strftime(time); }, }); __DATA__ laptop:~> monk.pl Benchmark: timing 10000000 iterations of cache, plain... cache: 79 wallclock secs (67.66 usr + 3.69 sys = 71.35 CPU) @ 14 +0154.17/s (n=10000000) plain: 282 wallclock secs (248.43 usr + 7.03 sys = 255.46 CPU) @ + 39145.07/s (n=10000000) Rate plain cache plain 39145/s -- -72% cache 140154/s 258% --
In reply to Wasting time with times by hossman
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |