1 module mutils.time; 2 3 import core.sys.windows.windows; 4 import core.sys.posix.sys.time; 5 6 // Replacement for deprecated std.datetime StopWatch, used mainly in benchmark tests 7 struct StopWatch { 8 long begin; 9 long end; 10 11 void start() { 12 begin = useconds(); 13 } 14 15 void stop() { 16 end = useconds(); 17 } 18 19 long secs() { 20 return (end - begin) / 1_000_000; 21 } 22 23 long msecs() { 24 long endTime = (end == 0) ? useconds() : end; 25 return (endTime - begin) / 1000; 26 } 27 28 long usecs() { 29 long endTime = (end == 0) ? useconds() : end; 30 return (endTime - begin); 31 } 32 33 } 34 35 enum long ticksPerSecond = 1_000_000; 36 37 // High precison timer, might be used for relative time measurements 38 long useconds() { 39 version (Posix) { 40 timeval t; 41 gettimeofday(&t, null); 42 return t.tv_sec * 1_000_000 + t.tv_usec; 43 } else version (Windows) { 44 __gshared double mul = -1; 45 if (mul < 0) { 46 long frequency; 47 int ok = QueryPerformanceFrequency(&frequency); 48 assert(ok); 49 mul = 1_000_000.0 / frequency; 50 } 51 long ticks; 52 int ok = QueryPerformanceCounter(&ticks); 53 assert(ok); 54 return cast(long)(ticks * mul); 55 } else { 56 static assert("OS not supported."); 57 } 58 } 59 60 unittest { 61 long ticks = useconds(); 62 assert(ticks > 0); 63 }