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 deprecated: 16 17 import std.datetime; 18 import ae.sys.timing; 19 20 MonoTime lastTime; 21 22 static this() 23 { 24 lastTime = MonoTime.currTime(); 25 } 26 27 Duration elapsedTime() 28 { 29 auto c = MonoTime.currTime(); 30 auto d = c - lastTime; 31 lastTime = c; 32 return d; 33 } 34 35 struct TimedAction 36 { 37 string name; 38 Duration duration; 39 } 40 41 TimedAction[] timedActions; 42 size_t[string] timeNameIndices; 43 string currentAction = null; 44 45 void timeEnd(string action = null) 46 { 47 if (action && currentAction && action != currentAction) 48 action = currentAction ~ " / " ~ action; 49 if (action is null) 50 action = currentAction; 51 if (action is null) 52 action = "other"; 53 currentAction = null; 54 55 // ordered 56 if (action !in timeNameIndices) 57 { 58 timeNameIndices[action] = timedActions.length; 59 timedActions ~= TimedAction(action, elapsedTime()); 60 } 61 else 62 timedActions[timeNameIndices[action]].duration += elapsedTime(); 63 } 64 65 66 void timeStart(string action = null) 67 { 68 timeEnd(); 69 currentAction = action; 70 } 71 72 void timeAction(string action, void delegate() p) 73 { 74 timeStart(action); 75 p(); 76 timeEnd(action); 77 } 78 79 void clearTimes() 80 { 81 timedActions = null; 82 timeNameIndices = null; 83 lastTime = MonoTime.currTime(); 84 } 85 86 /// Retrieves current times and clears them. 87 string getTimes()() 88 { 89 timeEnd(); 90 91 import std..string, std.array; 92 string[] lines; 93 int maxLength; 94 foreach (action; timedActions) 95 if (!action.duration.empty) 96 if (maxLength < action.name.length) 97 maxLength = action.name.length; 98 string fmt = format("%%%ds : %%10d (%%s)", maxLength); 99 foreach (action; timedActions) 100 if (!action.duration.empty) 101 lines ~= format(fmt, action.name, action.duration.total!"hnsecs", action.duration); 102 clearTimes(); 103 return join(lines, "\n"); 104 } 105 106 void dumpTimes()() 107 { 108 import std.stdio; 109 import ae.sys.console; 110 auto times = getTimes(); 111 if (times.length) 112 writeln(times); 113 } 114 115 private string[] timeStack; 116 117 void timePush(string action = null) 118 { 119 timeStack ~= currentAction; 120 timeStart(action); 121 } 122 123 void timePop(string action = null) 124 { 125 timeEnd(action); 126 timeStart(timeStack[$-1]); 127 timeStack = timeStack[0..$-1]; 128 }