aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/ext_depends/D-YAML/examples/yaml_bench/yaml_bench.d
blob: bb8446e2618f54e102f44563bcee32803a47e98c (plain)
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
module dyaml.yaml_bench;
//Benchmark that loads, and optionally extracts data from and/or emits a YAML file.

import std.algorithm;
import std.conv;
import std.datetime.systime;
import std.datetime.stopwatch;
import std.file;
import std.getopt;
import std.range;
import std.stdio;
import std.string;
import dyaml;

///Get data out of every node.
void extract(ref Node document) @safe
{
    void crawl(ref Node root) @safe
    {
        final switch (root.nodeID)
        {
            case NodeID.scalar:
                 switch(root.tag)
                {
                    case "tag:yaml.org,2002:null":      auto value = root.as!YAMLNull;  break;
                    case "tag:yaml.org,2002:bool":      auto value = root.as!bool;      break;
                    case "tag:yaml.org,2002:int":       auto value = root.as!long;      break;
                    case "tag:yaml.org,2002:float":     auto value = root.as!real;      break;
                    case "tag:yaml.org,2002:binary":    auto value = root.as!(ubyte[]); break;
                    case "tag:yaml.org,2002:timestamp": auto value = root.as!SysTime;   break;
                    case "tag:yaml.org,2002:str":       auto value = root.as!string;    break;
                    default: writeln("Unrecognozed tag: ", root.tag);
                }
                break;
            case NodeID.sequence:
                foreach(ref Node node; root)
                {
                    crawl(node);
                }
                break;
            case NodeID.mapping:
                foreach(ref Node key, ref Node value; root)
                {
                    crawl(key);
                    crawl(value);
                }
                break;
            case NodeID.invalid:
                assert(0);
        }
    }

    crawl(document);
}

void main(string[] args) //@safe
{
    import std.array : array;
    bool get = false;
    bool dump = false;
    bool reload = false;
    bool quiet = false;
    bool verbose = false;
    bool scanOnly = false;
    uint runs = 1;

    auto help = getopt(
        args,
        "get|g", "Extract data from the file (using Node.as()).", &get,
        "dump|d", "Dump the loaded data (to YAML_FILE.dump).", &dump,
        "runs|r", "Repeat parsing the file NUM times.", &runs,
        "reload", "Reload the file from the diskl on every repeat By default,"~
            " the file is loaded to memory once and repeatedly parsed from memory.", &reload,
        "quiet|q", "Don't print anything.", &quiet,
        "verbose|v", "Print even more.", &verbose,
        "scan-only|s", "Do not execute the entire parsing process, only scanning. Overrides '--dump'", &scanOnly
    );

    if (help.helpWanted || (args.length < 2))
    {
        defaultGetoptPrinter(
            "D:YAML benchmark\n"~
            "Copyright (C) 2011-2018 Ferdinand Majerech, Cameron \"Herringway\" Ross\n"~
            "Usage: yaml_bench [OPTION ...] [YAML_FILE]\n\n"~
            "Loads and optionally extracts data and/or dumps a YAML file.\n",
            help.options
        );
        return;
    }

    string file = args[1];

    auto stopWatch = StopWatch(AutoStart.yes);
    void[] fileInMemory;
    if(!reload) { fileInMemory = std.file.read(file); }
    void[] fileWorkingCopy = fileInMemory.dup;
    auto loadTime = stopWatch.peek();
    stopWatch.reset();
    try
    {
        // Instead of constructing a resolver/constructor with each Loader,
        // construct them once to remove noise when profiling.
        auto resolver    = Resolver.withDefaultResolvers;

        auto constructTime = stopWatch.peek();

        Node[] nodes;

        void runLoaderBenchmark() //@safe
        {
            // Loading the file rewrites the loaded buffer, so if we don't reload from
            // disk, we need to use a copy of the originally loaded file.
            if(reload) { fileInMemory = std.file.read(file); }
            else       { fileWorkingCopy[] = fileInMemory[]; }
            void[] fileToLoad = reload ? fileInMemory : fileWorkingCopy;

            auto loader        = Loader.fromBuffer(fileToLoad);
            if(scanOnly)
            {
                loader.scanBench();
                return;
            }

            loader.resolver = resolver;
            nodes = loader.array;
        }
        void runDumpBenchmark() @safe
        {
            if(dump)
            {
                dumper().dump(File(file ~ ".dump", "w").lockingTextWriter, nodes);
            }
        }
        void runGetBenchmark() @safe
        {
            if(get) foreach(ref node; nodes)
            {
                extract(node);
            }
        }
        auto totalTime = benchmark!(runLoaderBenchmark, runDumpBenchmark, runGetBenchmark)(runs);
        if (!quiet)
        {
            auto enabledOptions =
                only(
                    get ? "Get" : "",
                    dump ? "Dump" : "",
                    reload ? "Reload" : "",
                    scanOnly ? "Scan Only":  ""
                ).filter!(x => x != "");
            if (!enabledOptions.empty)
            {
                writefln!"Options enabled: %-(%s, %)"(enabledOptions);
            }
            if (verbose)
            {
                if (!reload)
                {
                    writeln("Time to load file: ", loadTime);
                }
                writeln("Time to set up resolver: ", constructTime);
            }
            writeln("Runs: ", runs);
            foreach(time, func, enabled; lockstep(totalTime[], only("Loader", "Dumper", "Get"), only(true, dump, get)))
            {
                if (enabled)
                {
                    writeln("Average time spent on ", func, ": ", time / runs);
                    writeln("Total time spent on ", func, ": ", time);
                }
            }
        }
    }
    catch(YAMLException e)
    {
        writeln("ERROR: ", e.msg);
    }
}