--- JSON-XS/eg/bench 2007/03/24 22:55:16 1.6 +++ JSON-XS/eg/bench 2008/03/19 04:08:22 1.18 @@ -2,11 +2,26 @@ # Usage: bench json-file -use JSON; +# which modules to test (JSON usually excluded because its so slow) +my %tst = ( +# "JSON" => ['JSON::objToJson $perl' , 'JSON::jsonToObj $json'], +# "JSON::PP" => ['$pp->encode ($perl)' , '$pp->decode ($json)'], + "JSON::DWIW" => ['$dwiw->to_json ($perl)' , '$dwiw->from_json ($json)'], +# "JSON::PC" => ['$pc->convert ($perl)' , '$pc->parse ($json)'], + "JSON::Syck" => ['JSON::Syck::Dump $perl' , 'JSON::Syck::Load $json'], + "JSON::XS" => ['encode_json $perl' , 'decode_json $json'], + "JSON::XS/2" => ['$xs2->encode ($perl)' , '$xs2->decode ($json)'], + "JSON::XS/3" => ['$xs3->encode ($perl)' , '$xs3->decode ($json)'], + "Storable" => ['Storable::nfreeze $perl' , 'Storable::thaw $pst'], +); + +use JSON (); use JSON::DWIW; use JSON::PC; -use JSON::XS; +use JSON::PP (); +use JSON::XS qw(encode_json decode_json); use JSON::Syck; +use Storable (); use Time::HiRes; use List::Util; @@ -15,6 +30,7 @@ my $dwiw = new JSON::DWIW; my $pc = new JSON::PC; +my $pp = JSON::PP->new->max_depth (512); my $xs2 = JSON::XS->new->utf8->pretty->canonical; my $xs3 = JSON::XS->new->utf8->shrink; @@ -23,6 +39,9 @@ local $/; $json = <>; +# fix syck-brokenised stuff +#$json = JSON::XS->new->ascii(1)->encode (JSON::Syck::Load $json); + #srand 0; $json = JSON::XS->new->utf8(1)->ascii(0)->encode ([join "", map +(chr rand 255), 0..2047]); #if (1) { @@ -35,42 +54,27 @@ # warn length $json; #} -my %tst = ( - "JSON" => ['objToJson $perl' , 'jsonToObj $json'], - "JSON::DWIW" => ['$dwiw->to_json ($perl)', '$dwiw->from_json ($json)'], - "JSON::PC" => ['$pc->convert ($perl)' , '$pc->parse ($json)'], - "JSON::Syck" => ['JSON::Syck::Dump $perl', 'JSON::Syck::Load $json'], - "JSON::XS" => ['to_json $perl' , 'from_json $json'], - "JSON::XS/2" => ['$xs2->encode ($perl)' , '$xs2->decode ($json)'], - "JSON::XS/3" => ['$xs3->encode ($perl)' , '$xs3->decode ($json)'], -); - sub bench($) { my ($code) = @_; - my $perl = jsonToObj $json; - my $count = 20; - my $times = 25; + my $perl = JSON::XS::decode_json $json; + my $pst = Storable::nfreeze $perl; + + my $count = 5; + my $times = 200; - my $cent = eval "sub { " . (join ";", ($code) x $count) . "}"; + my $cent = eval "sub { my \$t = Time::HiRes::time; " . (join ";", ($code) x $count) . "; Time::HiRes::time - \$t }"; $cent->(); - my @meas; + my $min = 1e99; - while () { - push @meas, Time::HiRes::time; - $cent->(); - $meas[-1] = Time::HiRes::time - $meas[-1]; - - my $mean = (List::Util::sum @meas) / @meas; - if (@meas >= $times) { - @meas = grep $_ > $mean * 0.9 && $_ < $mean * 1.1, @meas; - my @meas = grep $_ > $mean * 0.9999 && $_ < $mean * 1.1111, @meas; - if (@meas >= $times) { - return $count / $mean; - } - } + for (1..$times) { + my $t = $cent->(); + + $min = $t if $t < $min; } + + return $count / $min; } printf "%-10s | %10s | %10s |\n", "module", "encode", "decode";