1 /**
2  * Framework code for benchmarking individual functions.
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 <vladimir@thecybershadow.net>
12  */
13 
14 module ae.sys.benchmark;
15 version(Windows):
16 
17 import std.exception;
18 import core.memory;
19 
20 import ae.sys.windows.imports;
21 mixin(importWin32!q{windows});
22 
23 ulong rdtsc() { asm { rdtsc; } }
24 
25 private ulong benchStartTime;
26 
27 void benchStart()
28 {
29 	GC.collect();
30 	version(DOS) asm { cli; }
31 	benchStartTime = rdtsc();
32 }
33 
34 ulong benchEnd()
35 {
36 	auto time = rdtsc() - benchStartTime;
37 	version(DOS) asm { sti; }
38 	return time;
39 }
40 
41 static this()
42 {
43 	try
44 	{
45 		version(DOS)
46 		{}
47 		else
48 		{
49 			HANDLE proc = GetCurrentProcess();
50 			HANDLE thr  = GetCurrentThread();
51 
52 			HANDLE tok;
53 			enforce(OpenProcessToken(proc, TOKEN_ADJUST_PRIVILEGES, &tok), "OpenProcessToken");
54 
55 			LUID luid;
56 			enforce(LookupPrivilegeValue(null,
57 				"SeIncreaseBasePriorityPrivilege",
58 				&luid), "LookupPrivilegeValue");
59 
60 			TOKEN_PRIVILEGES tp;
61 			tp.PrivilegeCount = 1;
62 			tp.Privileges[0].Luid = luid;
63 			tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
64 
65 			AdjustTokenPrivileges(tok, FALSE, &tp, tp.sizeof, null, null);
66 			enforce(GetLastError() == ERROR_SUCCESS, "AdjustTokenPrivileges");
67 
68 			enforce(SetPriorityClass(proc, REALTIME_PRIORITY_CLASS), "SetPriorityClass");
69 		//	enforce(SetPriorityClass(proc, HIGH_PRIORITY_CLASS), "SetPriorityClass");
70 			enforce(SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL), "SetThreadPriority");
71 
72 			enforce(SetProcessAffinityMask(proc, 1), "SetProcessAffinityMask");
73 		}
74 	}
75 	catch (Exception e)
76 	{
77 		import std.stdio;
78 		writeln("Benchmark initialization error: ", e.msg);
79 	}
80 
81 	GC.disable();
82 }