0
|
1 // Written in the D programming language
|
|
2 // www.digitalmars.com/d/
|
|
3
|
|
4 /*
|
|
5 * The contents of this file are subject to the Mozilla Public License Version
|
|
6 * 1.1 (the "License"); you may not use this file except in compliance with
|
|
7 * the License. You may obtain a copy of the License at
|
|
8 * http://www.mozilla.org/MPL/
|
|
9 *
|
|
10 * Software distributed under the License is distributed on an "AS IS" basis,
|
|
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
|
|
12 * for the specific language governing rights and limitations under the
|
|
13 * License.
|
|
14 *
|
|
15 * The Original Code is the Dynamin library.
|
|
16 *
|
|
17 * The Initial Developer of the Original Code is Jordan Miner.
|
|
18 * Portions created by the Initial Developer are Copyright (C) 2006-2009
|
|
19 * the Initial Developer. All Rights Reserved.
|
|
20 *
|
|
21 * Contributor(s):
|
|
22 * Jordan Miner <jminer7@gmail.com>
|
|
23 *
|
|
24 */
|
|
25
|
|
26 module dynamin.core.benchmark;
|
|
27
|
|
28 import dynamin.all_core;
|
|
29 import dynamin.core.string;
|
|
30 import tango.io.Stdout;
|
|
31
|
|
32 /**
|
|
33 * Returns: The average number of milliseconds one call of the specified
|
|
34 * delegate took.
|
|
35 */
|
|
36 real benchmark(int repetitions, void delegate() dg) { // use static opCall()?
|
|
37 long time = Environment.runningTime;
|
|
38 for(int i = 0; i < repetitions; ++i)
|
|
39 dg();
|
|
40 return (Environment.runningTime-time)/cast(real)repetitions;
|
|
41 }
|
|
42 real benchmark(void delegate() dg) {
|
|
43 return benchmark(1, dg);
|
|
44 }
|
|
45 /**
|
|
46 * name can be null
|
|
47 */
|
|
48 real benchmarkAndWrite(string name, int repetitions, void delegate() dg) {
|
|
49 real time = benchmark(repetitions, dg);
|
|
50 Stdout.format("{} took {:.2}ms.", name, time).newline; // TODO: verify :.2
|
|
51 return time;
|
|
52 }
|
|
53 real benchmarkAndWrite(string name, void delegate() dg) {
|
|
54 return benchmarkAndWrite(name, 1, dg);
|
|
55 }
|
|
56
|
|
57 /**
|
|
58 * As the constructor calls the Start() method, the only time one would need
|
|
59 * to is when reusing a Benchmark object.
|
|
60 */
|
|
61 class Benchmark {
|
|
62 long _startTime;
|
|
63 this() {
|
|
64 start();
|
|
65 }
|
|
66 void start() {
|
|
67 _startTime = Environment.runningTime;
|
|
68 }
|
|
69 long time() {
|
|
70 return _startTime-Environment.runningTime;
|
|
71 }
|
|
72 void writeTime(string opName) {
|
|
73 if(opName is null)
|
|
74 opName = "Benchmark";
|
|
75 Stdout.format("{} took {}ms.", opName, time).newline;
|
|
76 }
|
|
77
|
|
78 /**
|
|
79 * calls the specified delegate the specified number of times and
|
|
80 * returns the average time one call took
|
|
81 */
|
|
82 static long measure(int times, void delegate() d) {
|
|
83 long time = Environment.runningTime;
|
|
84 for(int i = 0; i < times; ++i)
|
|
85 d();
|
|
86 return (Environment.runningTime-time)/times;
|
|
87 }
|
|
88 }
|