#!/home/ben/software/install/bin/perl
use warnings;
use strict;
use lib '/home/ben/projects/json-create/blib/lib';
use lib '/home/ben/projects/json-create/blib/arch';

use JSON::Create;
use JSON::XS;
use Cpanel::JSON::XS;

use Time::HiRes;
use List::Util;

use utf8;

my %tst = (
   "Cpanel::J::XS"      => [
       'Cpanel::JSON::XS::encode_json ($json)',
   ],
   "JSON::XS"      => [
       'JSON::XS::encode_json ($json)',
   ],
   "JSON::Create" => [
       'JSON::Create::create_json ($json)',
   ],
);


my $json = [
    'Higgins',
    'TC',
    'Magnum',
    'Hawaii',
    'Higgins',
    'TC',
    'Magnum',
    'Hawaii',
    'Links to the netherworld',
    'Shakespeare',
    'ferrari',
    '1234567890',
    'Selleck',
    'The old Clifford estate',
    'I did make a point of going in the daytime',
    'You\'re supposed to be dead',
    'Are you the one that hit me?',
    'Any particular reason?',
    'Why didn\'t you just call the police?',
    'GOT TO YOU',
]; 


my %json = @$json;

my $h2n = {
    a => 1,
    b => 2,
    c => 4,
    d => 8,
    e => 16,
    f => 32,
    g => 64,
    h => 128,
    i => 256,
    j => 512,
    k => 1024,
    l => 2048,
    m => 4096,
    n => 8192,
    o => 16384,
    p => 32768,
    q => 65536,
    r => 131_072,
    s => 262_144,
    t => 524_288,
    u => 1_048_576,
    v => 2_097_152,
    w => 4_194_304,
    x => 8_388_608,
    y => 16_777_216,
    z => 33_554_432,
    A => 67_108_864,
    B => 134_217_728,
    C => 268_435_456,
    D => 536_870_912,
    E => 1_073_741_824,
};


$json = \%json;

#$json = $h2n;

sub bench
{
    my ($code, $count) = @_;

    my $cent = eval "sub { my \$t = Time::HiRes::time; " . (join ";", ($code) x $count) . "; Time::HiRes::time - \$t }";
    $cent->();
    my $t = $cent->();

    return $t;
}


my %min;
my $min = 1e99;
my $count = 1000;
my $times = 100;
#my $count = 5;
#my $times = 5;

print "Repetitions: $count x $times = ", $count * $times, "\n";

printf "--------------+------------+------------+\n";
printf "%-13s | %10s | %10s |\n", "module", "1/min", "min";
printf "--------------|------------|------------|\n";

for my $module (sort keys %tst) {
    $min{$module} = $min;

    for (1..$times) {
	my $t = bench ($tst{$module}[0], $count);
	$min{$module} = $t if $t < $min{$module};
    }
}

for my $module (sort keys %tst) {
    printf "%-13s | %10.3f | %10.7f |\n", $module, $count/$min{$module}, $min{$module};
}
printf "--------------+------------+------------+\n";

