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