| 1 |
#!/opt/bin/perl |
| 2 |
|
| 3 |
# Usage: bench json-file |
| 4 |
|
| 5 |
# which modules to test (JSON usually excluded because its so slow) |
| 6 |
my %tst = ( |
| 7 |
"JSON" => ['objToJson $perl' , 'jsonToObj $json'], |
| 8 |
"JSON::DWIW" => ['$dwiw->to_json ($perl)', '$dwiw->from_json ($json)'], |
| 9 |
"JSON::PC" => ['$pc->convert ($perl)' , '$pc->parse ($json)'], |
| 10 |
"JSON::Syck" => ['JSON::Syck::Dump $perl', 'JSON::Syck::Load $json'], |
| 11 |
"JSON::XS" => ['to_json $perl' , 'from_json $json'], |
| 12 |
"JSON::XS/2" => ['$xs2->encode ($perl)' , '$xs2->decode ($json)'], |
| 13 |
"JSON::XS/3" => ['$xs3->encode ($perl)' , '$xs3->decode ($json)'], |
| 14 |
"Storable" => ['Storable::nfreeze $perl', 'Storable::thaw $pst'], |
| 15 |
); |
| 16 |
|
| 17 |
use JSON; |
| 18 |
use JSON::DWIW; |
| 19 |
use JSON::PC; |
| 20 |
use JSON::XS qw(to_json from_json); |
| 21 |
use JSON::Syck; |
| 22 |
use Storable (); |
| 23 |
|
| 24 |
use Time::HiRes; |
| 25 |
use List::Util; |
| 26 |
|
| 27 |
use utf8; |
| 28 |
|
| 29 |
my $dwiw = new JSON::DWIW; |
| 30 |
my $pc = new JSON::PC; |
| 31 |
my $xs2 = JSON::XS->new->utf8->pretty->canonical; |
| 32 |
my $xs3 = JSON::XS->new->utf8->shrink; |
| 33 |
|
| 34 |
my $json; # the test string |
| 35 |
|
| 36 |
local $/; |
| 37 |
$json = <>; |
| 38 |
|
| 39 |
# fix syck-brokenised stuff |
| 40 |
$json = JSON::XS->new->ascii(1)->encode (JSON::Syck::Load $json); |
| 41 |
|
| 42 |
#srand 0; $json = JSON::XS->new->utf8(1)->ascii(0)->encode ([join "", map +(chr rand 255), 0..2047]); |
| 43 |
|
| 44 |
#if (1) { |
| 45 |
# use Storable; |
| 46 |
# open my $fh, "<:unix", "/opt/crossfire/share/cfserver/faces" or die "$!"; |
| 47 |
# my $faces = Storable::thaw do { <$fh> }; |
| 48 |
# $json = objToJson $faces; |
| 49 |
# open my $fh2, ">:unix", "faces.json" or die "$!"; |
| 50 |
# print $fh2 $json; |
| 51 |
# warn length $json; |
| 52 |
#} |
| 53 |
|
| 54 |
sub bench($) { |
| 55 |
my ($code) = @_; |
| 56 |
|
| 57 |
my $perl = jsonToObj $json; |
| 58 |
my $pst = Storable::nfreeze $perl; |
| 59 |
|
| 60 |
my $count = 5; |
| 61 |
my $times = 200; |
| 62 |
|
| 63 |
my $cent = eval "sub { my \$t = Time::HiRes::time; " . (join ";", ($code) x $count) . "; Time::HiRes::time - \$t }"; |
| 64 |
$cent->(); |
| 65 |
|
| 66 |
my $min = 1e99; |
| 67 |
|
| 68 |
for (1..$times) { |
| 69 |
my $t = $cent->(); |
| 70 |
|
| 71 |
$min = $t if $t < $min; |
| 72 |
} |
| 73 |
|
| 74 |
return $count / $min; |
| 75 |
} |
| 76 |
|
| 77 |
printf "%-10s | %10s | %10s |\n", "module", "encode", "decode"; |
| 78 |
printf "-----------|------------|------------|\n"; |
| 79 |
for my $module (sort keys %tst) { |
| 80 |
my $enc = bench $tst{$module}[0]; |
| 81 |
my $dec = bench $tst{$module}[1]; |
| 82 |
|
| 83 |
printf "%-10s | %10.3f | %10.3f |\n", $module, $enc, $dec; |
| 84 |
} |
| 85 |
printf "-----------+------------+------------+\n"; |
| 86 |
|