File: bench.cpp

package info (click to toggle)
boost1.90 1.90.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 593,120 kB
  • sloc: cpp: 4,190,908; xml: 196,648; python: 34,618; ansic: 23,145; asm: 5,468; sh: 3,774; makefile: 1,161; perl: 1,020; sql: 728; ruby: 676; yacc: 478; java: 77; lisp: 24; csh: 6
file content (1184 lines) | stat: -rw-r--r-- 31,419 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/json
//

#include <boost/json/detail/config.hpp>

#if defined(BOOST_JSON_USE_SSE2)
#  define RAPIDJSON_SSE2
#  define SSE2_ARCH_SUFFIX "/sse2"
#else
#  define SSE2_ARCH_SUFFIX ""
#endif

#ifdef BOOST_JSON_HAS_NLOHMANN_JSON
# include "lib/nlohmann/single_include/nlohmann/json.hpp"
#endif // BOOST_JSON_HAS_NLOHMANN_JSON

#ifdef BOOST_JSON_HAS_RAPIDJSON
# include "lib/rapidjson/include/rapidjson/rapidjson.h"
# include "lib/rapidjson/include/rapidjson/document.h"
# include "lib/rapidjson/include/rapidjson/writer.h"
# include "lib/rapidjson/include/rapidjson/stringbuffer.h"
#endif // BOOST_JSON_HAS_RAPIDJSON

#include <boost/json.hpp>
#include <boost/json/basic_parser_impl.hpp>
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <memory>
#include <numeric>
#include <vector>

#include "test_suite.hpp"
#include "apache_builds.hpp"
#include "canada.hpp"
#include "citm_catalog.hpp"

/*  References

    https://github.com/nst/JSONTestSuite

    http://seriot.ch/parsing_json.php
*/

std::string s_tests = "ps";
std::string s_impls = "busorn";
std::size_t s_trials = 6;
std::string s_branch = "";
std::string s_alloc = "p";
std::string s_num_mode = "i";
std::string s_file_io = "n";

namespace boost {
namespace json {

using clock_type = std::chrono::steady_clock;

::test_suite::debug_stream dout(std::cerr);
std::stringstream strout;

#if defined(__clang__)
string_view toolset = "clang";
#elif defined(__GNUC__)
string_view toolset = "gcc";
#elif defined(_MSC_VER)
string_view toolset = "msvc";
#else
string_view toolset = "unknown";
#endif

#if BOOST_JSON_ARCH == 32
string_view arch = "x86" SSE2_ARCH_SUFFIX;
#elif BOOST_JSON_ARCH == 64
string_view arch = "x64" SSE2_ARCH_SUFFIX;
#else
#error Unknown architecture.
#endif

//----------------------------------------------------------

struct file_item
{
    string_view name;
    std::string text;
};

using file_list = std::vector<file_item>;

class any_impl
{
    std::string name_;
    parse_options popts_;
    bool with_file_io_;

    virtual
    clock_type::duration
    parse_string(file_item const& fi, std::size_t repeat) const = 0;

    virtual
    clock_type::duration
    parse_file(file_item const& fi, std::size_t repeat) const = 0;

    virtual
    clock_type::duration
    serialize_string(file_item const& fi, std::size_t repeat) const = 0;

protected:
    clock_type::duration
    skip() const
    {
        return clock_type::duration::zero();
    }

    parse_options const&
    get_parse_options() const noexcept
    {
        return popts_;
    }

public:
    using operation = auto (any_impl::*)
        (file_item const& fi, std::size_t repeat) const
        -> clock_type::duration;

    any_impl(
        string_view base_name,
        string_view flavor,
        bool is_boost,
        bool is_pool,
        bool with_file_io,
        parse_options const& popts)
        : popts_(popts)
        , with_file_io_(with_file_io)
    {
        std::string extra;
        switch( popts_.numbers )
        {
        case number_precision::precise:
            extra = "precise numbers";
            break;
        case number_precision::none:
            extra = "no numbers";
            break;
        default:
            break;
        }

        if( with_file_io_ )
        {
            if( !extra.empty() )
                extra += '+';
            extra += "file IO";
        }

        if( is_pool )
        {
            if( !extra.empty() )
                extra = '+' + extra;
            extra = "pool" + extra;
        }

        if( !flavor.empty() )
        {
            if( !extra.empty() )
                extra = '+' + extra;
            extra.insert( extra.begin(), flavor.begin(), flavor.end() );
        }

        if( !extra.empty() )
            extra = " (" + extra + ')';

        if( is_boost && !s_branch.empty() )
            extra += ' ' + s_branch;

        name_ = base_name;
        name_ += extra;
    }

    virtual ~any_impl() = default;

    clock_type::duration
    bench(string_view verb, file_item const& fi, std::size_t repeat) const
    {

        if(verb == "Parse")
        {
            if( with_file_io_ )
                return parse_file(fi, repeat);
            else
                return parse_string(fi, repeat);
        }
        else
        {
            BOOST_ASSERT( verb == "Serialize" );
            if( with_file_io_ )
                return skip();
            else
                return serialize_string(fi, repeat);
        }
    }

    string_view
    name() const noexcept
    {
        return name_;
    }
};

using impl_ptr = std::unique_ptr<any_impl const>;
using impl_list = std::vector<impl_ptr>;

std::string
load_file(char const* path)
{
    FILE* f = fopen(path, "rb");
    fseek(f, 0, SEEK_END);
    auto const size = ftell(f);
    std::string s;
    s.resize(size);
    fseek(f, 0, SEEK_SET);
    auto const nread =
        fread(&s[0], 1, size, f);
    s.resize(nread);
    fclose(f);
    return s;
}

struct sample
{
    std::size_t calls;
    std::size_t millis;
    std::size_t mbs;
};

// Returns the number of invocations per second
template<
    class Rep,
    class Period,
    class F>
sample
run_for(std::chrono::duration<Rep, Period> interval, F&& f)
{
    clock_type::duration elapsed(0);
    std::size_t n = 0;
    do
    {
        elapsed += f();
        ++n;
    }
    while(elapsed < interval);
    return { n, static_cast<std::size_t>(
        std::chrono::duration_cast<
            std::chrono::milliseconds>(
                elapsed).count()), 0 };
}

std::size_t
megabytes_per_second(
    file_item const& file, std::size_t calls, std::size_t millis)
{
    double result = file.text.size();
    result /= 1024 * 1024; // size in megabytes
    result *= calls;
    result /= millis; // mb per ms
    result *= 1000; // mb per s
    return static_cast<std::size_t>(0.5 + result); // round up
}

std::ostream&
print_prefix(
    std::ostream& os, file_item const& file, any_impl const& impl,
    string_view verb)
{
    return os << verb << " " << file.name << "," << toolset << " " <<
        arch << "," << impl.name();
}

void
bench(
    string_view verb,
    file_list const& vf,
    impl_list const& vi, std::size_t Trials)
{
    std::vector<sample> trial;
    for(unsigned i = 0; i < vf.size(); ++i)
    {
        for(unsigned j = 0; j < vi.size(); ++j)
        {
            trial.clear();
            std::size_t repeat = 1;

            auto const f = [&]{
                return vi[j].get()->bench(verb, vf[i], repeat);
            };

            // helps with the caching, which reduces noise; also, we determine
            // if this configuration should be skipped altogether
            auto const elapsed = f();
            if( elapsed == std::chrono::milliseconds::zero() )
            {
                print_prefix(dout, vf[i], *vi[j], verb)
                    << "," << "N/A"
                    << "," << "N/A"
                    << "," << "N/A"
                    << "\n";
                print_prefix(strout, vf[i], *vi[j], verb)
                    << "," << "N/A" << "\n";
                continue;
            }

            repeat = 1000;
            for(unsigned k = 0; k < Trials; ++k)
            {
                auto result = run_for(std::chrono::seconds(5), f);
                result.calls *= repeat;
                result.mbs = megabytes_per_second(
                    vf[i], result.calls, result.millis);
                print_prefix(dout, vf[i], *vi[j], verb)
                    << "," << result.calls
                    << "," << result.millis
                    << "," << result.mbs
                    << "\n";
                trial.push_back(result);
                // adjust repeat to avoid overlong tests
                repeat = 250 * result.calls / result.millis;
            }

            // clean up the samples
            std::sort(
                trial.begin(),
                trial.end(),
                [](sample const& lhs, sample const& rhs)
                {
                    return lhs.mbs < rhs.mbs;
                });
            if(Trials >= 6)
            {
                // discard worst 2
                trial.erase(trial.begin(), trial.begin() + 2);
                // discard best 1
                trial.resize(trial.size() - 1);
            }
            else if(Trials > 3)
            {
                trial.erase(trial.begin(), trial.begin() + Trials - 3);
            }
            // average
            auto const calls = std::accumulate(
                trial.begin(), trial.end(),
                std::size_t{},
                [](std::size_t lhs, sample const& rhs)
                {
                    return lhs + rhs.calls;
                });
            auto const millis = std::accumulate(
                trial.begin(), trial.end(),
                std::size_t{},
                [](std::size_t lhs, sample const& rhs)
                {
                    return lhs + rhs.millis;
                });
            auto const mbs = megabytes_per_second(vf[i], calls, millis);
            print_prefix(strout, vf[i], *vi[j], verb) << "," << mbs << "\n";
        }
    }
}

//----------------------------------------------------------

class base_boost_impl : public any_impl
{
protected:
    bool is_pool_;

public:
    base_boost_impl(
        string_view flavor,
        bool is_pool,
        bool with_file_io,
        parse_options const& popts)
        : any_impl("boost", flavor, true, is_pool, with_file_io, popts)
        , is_pool_(is_pool)
    {}
};

//----------------------------------------------------------

class boost_impl : public base_boost_impl
{
public:
    boost_impl(bool is_pool, bool with_file_io, parse_options const& popts)
        : base_boost_impl("", is_pool, with_file_io, popts)
    {}

    clock_type::duration
    parse_string(file_item const& fi, std::size_t repeat) const override
    {
        auto const start = clock_type::now();
        parser p( {}, get_parse_options() );
        while(repeat--)
        {
            monotonic_resource mr;
            storage_ptr sp;
            if( is_pool_ )
                sp = &mr;
            p.reset( std::move(sp) );

            p.write( fi.text.data(), fi.text.size() );
            auto jv = p.release();
            (void)jv;
        }
        return clock_type::now() - start;
    }

    clock_type::duration
    parse_file(file_item const& fi, std::size_t repeat) const override
    {
        auto const start = clock_type::now();
        stream_parser p( {}, get_parse_options() );
        char s[ BOOST_JSON_STACK_BUFFER_SIZE];
        while(repeat--)
        {
            monotonic_resource mr;
            storage_ptr sp;
            if( is_pool_ )
                sp = &mr;
            p.reset( std::move(sp) );

            FILE* f = fopen(fi.name.data(), "rb");

            while( true )
            {
                std::size_t const sz = fread(s, 1, sizeof(s), f);
                if( ferror(f) )
                    break;

                p.write(s, sz);

                if( feof(f) )
                    break;
            }

            p.finish();
            auto jv = p.release();

            fclose(f);
        }
        return clock_type::now() - start;
    }

    clock_type::duration
    serialize_string(file_item const& fi, std::size_t repeat) const override
    {
        monotonic_resource mr;
        storage_ptr sp;
        if( is_pool_ )
            sp = &mr;
        value jv = json::parse( fi.text, std::move(sp) );

        auto const start = clock_type::now();
        serializer sr;
        string out;
        out.reserve(512);
        while(repeat--)
        {
            sr.reset(&jv);
            out.clear();
            for(;;)
            {
                out.grow(sr.read(
                    out.end(),
                    out.capacity() -
                        out.size()).size());
                if(sr.done())
                    break;
                out.reserve(
                    out.capacity() + 1);
            }
        }
        return clock_type::now() - start;
    }
};

//----------------------------------------------------------

class boost_null_impl : public base_boost_impl
{
    struct null_parser
    {
        struct handler
        {
            constexpr static std::size_t max_object_size = std::size_t(-1);
            constexpr static std::size_t max_array_size = std::size_t(-1);
            constexpr static std::size_t max_key_size = std::size_t(-1);
            constexpr static std::size_t max_string_size = std::size_t(-1);

            bool on_document_begin(system::error_code&) { return true; }
            bool on_document_end(system::error_code&) { return true; }
            bool on_object_begin(system::error_code&) { return true; }
            bool on_object_end(std::size_t, system::error_code&) { return true; }
            bool on_array_begin(system::error_code&) { return true; }
            bool on_array_end(std::size_t, system::error_code&) { return true; }
            bool on_key_part(string_view, std::size_t, system::error_code&) { return true; }
            bool on_key( string_view, std::size_t, system::error_code&) { return true; }
            bool on_string_part(string_view, std::size_t, system::error_code&) { return true; }
            bool on_string(string_view, std::size_t, system::error_code&) { return true; }
            bool on_number_part(string_view, system::error_code&) { return true; }
            bool on_int64(std::int64_t, string_view, system::error_code&) { return true; }
            bool on_uint64(std::uint64_t, string_view, system::error_code&) { return true; }
            bool on_double(double, string_view, system::error_code&) { return true; }
            bool on_bool(bool, system::error_code&) { return true; }
            bool on_null(system::error_code&) { return true; }
            bool on_comment_part(string_view, system::error_code&) { return true; }
            bool on_comment(string_view, system::error_code&) { return true; }
        };

        basic_parser<handler> p_;

        null_parser(parse_options const& popts)
            : p_(popts)
        {
        }

        void
        reset()
        {
            p_.reset();
        }

        std::size_t
        write(
            char const* data,
            std::size_t size,
            system::error_code& ec)
        {
            auto const n = p_.write_some(
                false, data, size, ec);
            if(! ec && n < size)
                ec = error::extra_data;
            return n;
        }

        std::size_t
        write_some(
            char const* data,
            std::size_t size,
            system::error_code& ec)
        {
            return p_.write_some(
                true, data, size, ec);
        }

        void
        finish(system::error_code& ec)
        {
            p_.write_some(false, nullptr, 0, ec);
        }
    };

public:
    boost_null_impl(bool with_file_io, parse_options const& popts)
        : base_boost_impl("null", false, with_file_io, popts)
    {}

    clock_type::duration
    parse_string(file_item const& fi, std::size_t repeat) const override
    {
        auto const start = clock_type::now();
        null_parser p( get_parse_options() );
        while(repeat--)
        {
            p.reset();
            system::error_code ec;
            p.write(fi.text.data(), fi.text.size(), ec);
            if( ec.failed() )
                throw system::system_error( ec );
        }
        return clock_type::now() - start;
    }

    clock_type::duration
    parse_file(file_item const& fi, std::size_t repeat) const override
    {
        auto const start = clock_type::now();
        null_parser p( get_parse_options() );
        char s[ BOOST_JSON_STACK_BUFFER_SIZE];
        while(repeat--)
        {
            p.reset();

            FILE* f = fopen(fi.name.data(), "rb");

            system::error_code ec;
            while( true )
            {
                std::size_t const sz = fread(s, 1, sizeof(s), f);
                if( ferror(f) )
                {
                    ec = std::io_errc::stream;
                    break;
                }

                p.write_some( s, sz, ec );
                if( ec.failed() )
                    break;

                if( feof(f) )
                    break;
            }

            fclose(f);

            if( ec.failed() )
                throw system::system_error( ec );
        }
        return clock_type::now() - start;
    }

    clock_type::duration
    serialize_string(file_item const&, std::size_t) const override
    {
        return skip();
    }
};

//----------------------------------------------------------

class boost_simple_impl : public base_boost_impl
{
public:
    boost_simple_impl(
        bool is_pool, bool with_file_io, parse_options const& popts)
        : base_boost_impl("convenient", is_pool, with_file_io, popts)
    {}

    clock_type::duration
    parse_string(file_item const& fi, std::size_t repeat) const override
    {
        auto const start = clock_type::now();
        while(repeat--)
        {
            monotonic_resource mr;
            storage_ptr sp;
            if( is_pool_ )
                sp = &mr;

            auto jv = json::parse(
                fi.text, std::move(sp), get_parse_options() );
            (void)jv;
        }
        return clock_type::now() - start;
    }

    clock_type::duration
    parse_file(file_item const& fi, std::size_t repeat) const override
    {
        auto const start = clock_type::now();
        while(repeat--)
        {
            std::ifstream is( fi.name, std::ios::in | std::ios::binary );

            monotonic_resource mr;
            storage_ptr sp;
            if( is_pool_ )
                sp = &mr;

            auto jv = json::parse( is, std::move(sp), get_parse_options() );
            (void)jv;
        }
        return clock_type::now() - start;
    }

    clock_type::duration
    serialize_string(file_item const& fi, std::size_t repeat) const override
    {
        monotonic_resource mr;
        storage_ptr sp;
        if( is_pool_ )
            sp = &mr;
        auto jv = json::parse( fi.text, std::move(sp) );

        auto const start = clock_type::now();
        std::string out;
        while(repeat--)
            out = json::serialize(jv);
        return clock_type::now() - start;
    }
};

//----------------------------------------------------------

class boost_operator_impl : public base_boost_impl
{
public:
    boost_operator_impl(
        bool is_pool, bool with_file_io, parse_options const& popts)
        : base_boost_impl("operators", is_pool, with_file_io, popts)
    {}

    clock_type::duration
    parse_string(file_item const& fi, std::size_t repeat) const override
    {
        std::istringstream is(fi.text);
        is.exceptions(std::ios::failbit);

        auto const start = clock_type::now();
        while(repeat--)
        {
            monotonic_resource mr;
            storage_ptr sp;
            if( is_pool_ )
                sp = &mr;

            value jv( std::move(sp) );
            is.seekg(0);
            is >> get_parse_options() >> jv;
        }
        return clock_type::now() - start;
    }

    clock_type::duration
    parse_file(file_item const& fi, std::size_t repeat) const override
    {
        auto const start = clock_type::now();
        while(repeat--)
        {
            monotonic_resource mr;
            storage_ptr sp;
            if( is_pool_ )
                sp = &mr;

            std::ifstream is( fi.name, std::ios::in | std::ios::binary );
            is.exceptions(std::ios::failbit);

            value jv( std::move(sp) );
            is >> get_parse_options() >> jv;
        }
        return clock_type::now() - start;
    }

    clock_type::duration
    serialize_string(file_item const& fi, std::size_t repeat) const override
    {
        monotonic_resource mr;
        storage_ptr sp;
        if( is_pool_ )
            sp = &mr;

        auto jv = json::parse( fi.text, std::move(sp) );

        auto const start = clock_type::now();
        std::string out;
        while(repeat--)
        {
            std::ostringstream os;
            os.exceptions(std::ios::failbit);
            os << jv;
            out = os.str();
        }
        return clock_type::now() - start;
    }
};

//----------------------------------------------------------

#ifdef BOOST_JSON_HAS_RAPIDJSON
template<class Allocator, bool FullPrecision>
struct rapidjson_impl : public any_impl
{
    static constexpr unsigned parse_flags
        = rapidjson::kParseDefaultFlags
        | (FullPrecision
                ? rapidjson::kParseFullPrecisionFlag
                : rapidjson::kParseNoFlags);

    static
    parse_options
    make_parse_options() noexcept
    {
        parse_options opts;
        opts.numbers = FullPrecision
            ? number_precision::precise : number_precision::imprecise;
        return opts;
    }

    rapidjson_impl(bool with_file_io)
        : any_impl(
            "rapidjson",
            "",
            false,
            std::is_same<Allocator, RAPIDJSON_DEFAULT_ALLOCATOR>::value,
            with_file_io,
            make_parse_options() )
    {}

    clock_type::duration
    parse_string(file_item const& fi, std::size_t repeat) const override
    {
        using namespace rapidjson;
        auto const start = clock_type::now();
        while(repeat--)
        {
            Allocator alloc;
            GenericDocument<UTF8<>, Allocator> d(&alloc);
            d.template Parse<rapidjson_impl::parse_flags>(
                fi.text.data(), fi.text.size() );
        }
        return clock_type::now() - start;
    }

    clock_type::duration
    parse_file(file_item const& fi, std::size_t repeat) const override
    {
        using namespace rapidjson;

        auto const start = clock_type::now();
        char* s = new char[ fi.text.size() ];
        std::unique_ptr<char[]> holder(s);

        while(repeat--)
        {
            FILE* f = fopen(fi.name.data(), "rb");
            std::size_t const sz = fread(s, 1, fi.text.size(), f);

            Allocator alloc;
            GenericDocument<UTF8<>, Allocator> d(&alloc);
            d.template Parse<rapidjson_impl::parse_flags>(s, sz);

            fclose(f);
        }
        return clock_type::now() - start;
    }

    clock_type::duration
    serialize_string(file_item const& fi, std::size_t repeat) const override
    {
        using namespace rapidjson;
        Allocator alloc;
        GenericDocument<UTF8<>, Allocator> d(&alloc);
        d.template Parse<rapidjson_impl::parse_flags>( fi.text.data(), fi.text.size() );

        auto const start = clock_type::now();
        rapidjson::StringBuffer st;
        while(repeat--)
        {
            st.Clear();
            rapidjson::Writer<rapidjson::StringBuffer> wr(st);
            d.Accept(wr);
        }
        return clock_type::now() - start;
    }
};
#endif // BOOST_JSON_HAS_RAPIDJSON

//----------------------------------------------------------

#ifdef BOOST_JSON_HAS_NLOHMANN_JSON
struct nlohmann_impl : public any_impl
{
    nlohmann_impl(bool with_file_io)
        : any_impl(
            "nlohmann",
            "",
            false,
            false,
            with_file_io,
            parse_options() )
    {}

    clock_type::duration
    parse_string(file_item const& fi, std::size_t repeat) const override
    {
        auto const start = clock_type::now();
        while(repeat--)
        {
            auto jv = nlohmann::json::parse( fi.text.begin(), fi.text.end() );
        }
        return clock_type::now() - start;
    }

    clock_type::duration
    parse_file(file_item const& fi, std::size_t repeat) const override
    {
        auto const start = clock_type::now();
        char* s = new char[ fi.text.size() ];
        std::unique_ptr<char[]> holder(s);

        while(repeat--)
        {
            FILE* f = fopen(fi.name.data(), "rb");
            std::size_t const sz = fread(s, 1, fi.text.size(), f);

            auto jv = nlohmann::json::parse(s, s + sz);

            fclose(f);
        }
        return clock_type::now() - start;
    }

    clock_type::duration
    serialize_string(file_item const& fi, std::size_t repeat) const override
    {
        auto jv = nlohmann::json::parse( fi.text.begin(), fi.text.end() );

        auto const start = clock_type::now();
        while(repeat--)
            auto st = jv.dump();
        return clock_type::now() - start;
    }
};
#endif // BOOST_JSON_HAS_NLOHMANN_JSON

} // json
} // boost

//

using namespace boost::json;

static bool parse_option( char const* s )
{
    if( *s == 0 )
        return false;

    char opt = *s++;

    if( *s++ != ':' )
        return false;

    switch( opt )
    {
    case 't':
        s_tests = s;
        break;

    case 'i':
        s_impls = s;
        break;

    case 'n':
        {
            int k = std::atoi( s );

            if( k > 0 )
                s_trials = k;
            else
                return false;
        }
        break;

    case 'b':
        s_branch = s;
        break;

    case 'a':
        s_alloc = s;
        break;

    case 'm':
        s_num_mode = s;
        break;

    case 'f':
        s_file_io = s;
        break;
    }

    return true;
}

bool add_impl(
    impl_list & vi, char kind, char alloc, char io, char num)
{
    parse_options popts;
    switch(num)
    {
    case 'i':
        popts.numbers = number_precision::imprecise;
        break;
    case 'p':
        popts.numbers = number_precision::precise;
        break;
    case 'n':
        popts.numbers = number_precision::none;
        break;
    default:
        return false;
    }
    bool const with_file_io = io == 'y';
    bool const is_pool = alloc == 'p';

    impl_ptr impl;
    switch( kind )
    {
    case 'b':
        impl.reset(
            new boost_impl(is_pool, with_file_io, popts) );
        break;

    case 'u':
        impl.reset(
            new boost_null_impl(with_file_io, popts) );
        break;

    case 's':
        impl.reset(
            new boost_simple_impl(
                is_pool, with_file_io, popts) );
        break;

    case 'o':
        impl.reset(
            new boost_operator_impl(
                is_pool, with_file_io, popts) );
        break;

#ifdef BOOST_JSON_HAS_RAPIDJSON
    case 'r':
        if(is_pool)
        {
            using Allocator = RAPIDJSON_DEFAULT_ALLOCATOR;
            if(popts.numbers == number_precision::precise)
                impl.reset(
                    new rapidjson_impl<Allocator, true>(with_file_io) );
            else
                impl.reset(
                    new rapidjson_impl<Allocator, false>(with_file_io) );
        }
        else
        {
            using Allocator = rapidjson::CrtAllocator;
            if(popts.numbers == number_precision::precise)
                impl.reset(
                    new rapidjson_impl<Allocator, true>(with_file_io) );
            else
                impl.reset(
                    new rapidjson_impl<Allocator, false>( with_file_io) );
        }
        break;
#endif // BOOST_JSON_HAS_RAPIDJSON

#ifdef BOOST_JSON_HAS_NLOHMANN_JSON
    case 'n':
        impl.reset( new nlohmann_impl(with_file_io) );
        break;
#endif // BOOST_JSON_HAS_NLOHMANN_JSON

    default:
        std::cerr << "Unknown implementation: '" << kind << "'\n";
        return false;
    }

    vi.emplace_back( std::move(impl) );
    return true;
}

static bool do_test( file_list const & vf, impl_list const & vi, char test )
{
    switch( test )
    {
    case 'p':
        bench("Parse", vf, vi, s_trials);
        break;

    case 's':
        bench("Serialize", vf, vi, s_trials);
        break;

    default:
        std::cerr << "Unknown test type: '" << test << "'\n";
        return false;
    }

    return true;
}

int
main(
    int const argc,
    char const* const* const argv)
{
    if( argc < 2 )
    {
        std::cerr <<
            "Usage: bench [options...] <file>...\n"
            "\n"
            "Options: -t:[p][s]                Test parsing, serialization or both\n"
            "            (default both)\n"
            "         -i:[b][u][s][o][d][r][n] Test the specified implementations\n"
            "            (b: Boost.JSON)\n"
            "            (u: Boost.JSON, null parser)\n"
            "            (s: Boost.JSON, convenient functions)\n"
            "            (o: Boost.JSON, stream operators)\n"
#ifdef BOOST_JSON_HAS_RAPIDJSON
            "            (r: RapidJSON)\n"
#endif // BOOST_JSON_HAS_RAPIDJSON
#ifdef BOOST_JSON_HAS_NLOHMANN_JSON
            "            (n: nlohmann/json)\n"
#endif // BOOST_JSON_HAS_NLOHMANN_JSON
            "            (default all)\n"
            "         -a:[p][d]                Memory allocation strategy\n"
            "            (p: memory pool)\n"
            "            (d: default strategy)\n"
            "            (default memory pool)\n"
            "         -n:<number>              Number of trials (default 6)\n"
            "         -b:<branch>              Branch label for boost implementations\n"
            "         -m:[i][p][n]             Number parsing mode\n"
            "            (i: imprecise)\n"
            "            (p: precise)\n"
            "            (n: none)\n"
            "            (default imprecise)\n"
            "         -f:[y][n]                Include file IO into consideration when testing parsers\n"
            "            (y: yes)\n"
            "            (n: no)\n"
            "            (default no)\n"
        ;

        return 4;
    }

    file_list vf;

    for( int i = 1; i < argc; ++i )
    {
        char const* s = argv[ i ];

        if( *s == '-' )
        {
            if( !parse_option( s+1 ) )
                std::cerr << "Unrecognized or incorrect option: '" << s << "'\n";
        }
        else
        {
            vf.emplace_back( file_item{ argv[i], load_file( s ) } );
        }
    }

    try
    {
        impl_list vi;

        for( char impl: s_impls )
            for( char alloc: s_alloc )
                for( char num: s_num_mode )
                    for( char io: s_file_io )
                        add_impl( vi, impl, alloc, io, num );

        // remove duplicate implementations
        std::sort(
            vi.begin(),
            vi.end(),
            [](impl_ptr const& l, impl_ptr const& r)
            {
                return l->name() < r->name();
            });
        auto const it = std::unique(
            vi.begin(),
            vi.end(),
            [](impl_ptr const& l, impl_ptr const& r)
            {
                return l->name() == r->name();
            });
        vi.erase( it, vi.end() );

        for( char ch: s_tests )
            do_test( vf, vi, ch );

        dout << "\n" << strout.str();
    }
    catch(boost::system::system_error const& se)
    {
        dout << se.what() << std::endl;
    }

    return 0;
}