Impressive how this script was transmitted to us from one year in the future ;-)
In the real code, will you be using subs like your compareAsString, or will you just write sort @whatever? If the latter, then here you're benchmarking code that you've artificially slowed down with the overhead of lots of sub calls.
Also, you might be surprised at the results: the Schwartzian Transform won't give you any improvement for simple comparisons! More specifically, you'll have no performance gain as long as the overhead of the two transforms is greater than the performance gain of the actual sort (makes sense, no?). Throwing in a usleep(1), as you did, will show you that, but you're still not testing the execution time of actual code.
So what the previous two paragraphs are getting at: What is the actual, specific code you'd like to benchmark?
The code itself is a bit problematic: You've declared all of your subs with an empty prototype, but then they all have parameters, which only works because you're using the older &subname calling syntax, which avoids prototypes. And, you're re-using the variable names $a and $b, which are special in sort functions (not necessarily wrong, just confusing). I'd just write these short sort routines inline.
Also, you could be using the Benchmark module to do your benchmarks for you. Here's a quick example (disclaimer: I'm not a Benchmarking expert but I hope I got it right).
#!/usr/bin/env perl use warnings; use strict; use Benchmark 'cmpthese'; use List::Util 'shuffle'; use Data::Dumper; my @sorted; my @input = map { 'F' x (int(rand(100))+1) } 1 .. 1000; #print Dumper(\@input); cmpthese(1000, { simple => sub { @sorted = sort { length($a)<=>length($b) } shuffle @input; }, schwartz => sub { @sorted = map { $$_[0] } sort { $$a[1]<=>$$b[1] } map { [$_,length($_)] } shuffle @input; }, }); #print Dumper(\@sorted);
The results I get are something like this:
Rate schwartz simple schwartz 249/s -- -47% simple 472/s 90% --
I.e. the normal sort is almost twice as fast! However, once you start making the criteria more complex (in the example replace length() with some_complex_computation()), then you'll start seeing the performance boost.
In reply to Re: Benchmark Schwartzian Transform
by Anonymous Monk
in thread Benchmark Schwartzian Transform
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |