1 /**
2 Copyright: Copyright (c) 2018, Joakim Brännström. All rights reserved.
3 License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0)
4 Author: Joakim Brännström (joakim.brannstrom@gmx.com)
5 */
6 module datacat_test.common;
7 
8 import core.time : Duration;
9 import logger = std.experimental.logger;
10 
11 immutable ResultFileExt = ".csv";
12 
13 struct BenchResult {
14     string name;
15     Duration total;
16     Duration lowest = Duration.max;
17 
18     this(string name) {
19         this.name = name;
20     }
21 
22     ~this() {
23         import std.file : exists;
24         import std.stdio : File;
25 
26         auto fname = name ~ ResultFileExt;
27 
28         try {
29             if (!exists(fname))
30                 File(fname, "w").writeln(`"lowest(usec)","total(usec)"`);
31             File(fname, "a").writefln(`"%s","%s"`, lowest.total!"usecs", total.total!"usecs");
32         } catch (Exception e) {
33             logger.error(e.msg);
34         }
35     }
36 
37     string toString() {
38         import std.format : format;
39 
40         return format(`lowest(%s) total(%s)`, lowest, total);
41     }
42 }
43 
44 auto benchmark(alias fn)(int times, string func = __FUNCTION__) {
45     import std.datetime.stopwatch : StopWatch;
46     import std.typecons : Yes, RefCounted;
47     import std.stdio;
48 
49     auto res = RefCounted!BenchResult(func);
50     foreach (const i; 0 .. times) {
51         auto sw = StopWatch(Yes.autoStart);
52         auto fnres = fn();
53         sw.stop;
54         if (sw.peek < res.lowest)
55             res.lowest = sw.peek;
56         res.total += sw.peek;
57     }
58 
59     return res;
60 }