1 /** 2 * Simple benchmarking/profiling code 3 * 4 * License: 5 * This Source Code Form is subject to the terms of 6 * the Mozilla Public License, v. 2.0. If a copy of 7 * the MPL was not distributed with this file, You 8 * can obtain one at http://mozilla.org/MPL/2.0/. 9 * 10 * Authors: 11 * Vladimir Panteleev <ae@cy.md> 12 */ 13 14 deprecated module ae.utils.bench; 15 16 // https://issues.dlang.org/show_bug.cgi?id=23965 17 // deprecated: 18 19 import std.datetime; 20 import ae.sys.timing; 21 22 MonoTime lastTime; 23 24 static this() 25 { 26 lastTime = MonoTime.currTime(); 27 } 28 29 Duration elapsedTime() 30 { 31 auto c = MonoTime.currTime(); 32 auto d = c - lastTime; 33 lastTime = c; 34 return d; 35 } 36 37 struct TimedAction 38 { 39 string name; 40 Duration duration; 41 } 42 43 TimedAction[] timedActions; 44 size_t[string] timeNameIndices; 45 string currentAction = null; 46 47 void timeEnd(string action = null) 48 { 49 if (action && currentAction && action != currentAction) 50 action = currentAction ~ " / " ~ action; 51 if (action is null) 52 action = currentAction; 53 if (action is null) 54 action = "other"; 55 currentAction = null; 56 57 // ordered 58 if (action !in timeNameIndices) 59 { 60 timeNameIndices[action] = timedActions.length; 61 timedActions ~= TimedAction(action, elapsedTime()); 62 } 63 else 64 timedActions[timeNameIndices[action]].duration += elapsedTime(); 65 } 66 67 68 void timeStart(string action = null) 69 { 70 timeEnd(); 71 currentAction = action; 72 } 73 74 void timeAction(string action, void delegate() p) 75 { 76 timeStart(action); 77 p(); 78 timeEnd(action); 79 } 80 81 void clearTimes() 82 { 83 timedActions = null; 84 timeNameIndices = null; 85 lastTime = MonoTime.currTime(); 86 } 87 88 /// Retrieves current times and clears them. 89 string getTimes()() 90 { 91 timeEnd(); 92 93 import std.string, std.array; 94 string[] lines; 95 int maxLength; 96 foreach (action; timedActions) 97 if (!action.duration.empty) 98 if (maxLength < action.name.length) 99 maxLength = action.name.length; 100 string fmt = format("%%%ds : %%10d (%%s)", maxLength); 101 foreach (action; timedActions) 102 if (!action.duration.empty) 103 lines ~= format(fmt, action.name, action.duration.total!"hnsecs", action.duration); 104 clearTimes(); 105 return join(lines, "\n"); 106 } 107 108 void dumpTimes()() 109 { 110 import std.stdio; 111 import ae.sys.console; 112 auto times = getTimes(); 113 if (times.length) 114 writeln(times); 115 } 116 117 private string[] timeStack; 118 119 void timePush(string action = null) 120 { 121 timeStack ~= currentAction; 122 timeStart(action); 123 } 124 125 void timePop(string action = null) 126 { 127 timeEnd(action); 128 timeStart(timeStack[$-1]); 129 timeStack = timeStack[0..$-1]; 130 }