|
3 | 3 |
|
4 | 4 | import gc |
5 | 5 | import json |
| 6 | +import os |
6 | 7 | import sys |
7 | 8 | import time |
8 | 9 | from pathlib import Path |
9 | 10 | from statistics import median |
10 | 11 |
|
11 | 12 |
|
| 13 | +def set_high_priority_and_affinity(): |
| 14 | + """Set high process priority and pin to a single CPU core for stable benchmarks.""" |
| 15 | + try: |
| 16 | + import psutil |
| 17 | + proc = psutil.Process() |
| 18 | + |
| 19 | + # Set high priority (below realtime, but above normal) |
| 20 | + if sys.platform == "win32": |
| 21 | + proc.nice(psutil.HIGH_PRIORITY_CLASS) |
| 22 | + else: |
| 23 | + # Unix: lower nice = higher priority, -10 is high but not root-only |
| 24 | + try: |
| 25 | + proc.nice(-10) |
| 26 | + except PermissionError: |
| 27 | + proc.nice(0) # At least normal priority |
| 28 | + |
| 29 | + # Pin to first CPU core to avoid migration overhead |
| 30 | + proc.cpu_affinity([0]) |
| 31 | + |
| 32 | + return True |
| 33 | + except ImportError: |
| 34 | + # psutil not available, try platform-specific fallbacks |
| 35 | + if sys.platform == "win32": |
| 36 | + try: |
| 37 | + import ctypes |
| 38 | + # Set high priority |
| 39 | + ctypes.windll.kernel32.SetPriorityClass( |
| 40 | + ctypes.windll.kernel32.GetCurrentProcess(), |
| 41 | + 0x00000080 # HIGH_PRIORITY_CLASS |
| 42 | + ) |
| 43 | + # Set affinity to first core |
| 44 | + ctypes.windll.kernel32.SetProcessAffinityMask( |
| 45 | + ctypes.windll.kernel32.GetCurrentProcess(), |
| 46 | + 1 # First CPU core |
| 47 | + ) |
| 48 | + return True |
| 49 | + except Exception: |
| 50 | + pass |
| 51 | + return False |
| 52 | + except Exception: |
| 53 | + return False |
| 54 | + |
| 55 | + |
12 | 56 | def main(): |
13 | 57 | positions_file = Path(sys.argv[1]) |
14 | 58 | warmup = int(sys.argv[2]) |
15 | 59 | rounds = int(sys.argv[3]) |
16 | 60 |
|
| 61 | + # Set high priority and CPU affinity for stable measurements |
| 62 | + priority_set = set_high_priority_and_affinity() |
| 63 | + |
17 | 64 | positions = json.loads(positions_file.read_text())["positions"] |
18 | 65 |
|
19 | 66 | from draughts import get_board |
@@ -50,6 +97,7 @@ def main(): |
50 | 97 | "times": times, |
51 | 98 | "median_ms": median(times) * 1000, |
52 | 99 | "positions_count": len(clean_positions), |
| 100 | + "high_priority": priority_set, |
53 | 101 | } |
54 | 102 | print(json.dumps(result)) |
55 | 103 |
|
|
0 commit comments