-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
480 lines (437 loc) · 24.1 KB
/
Program.cs
File metadata and controls
480 lines (437 loc) · 24.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Threading;
using System.ServiceProcess;
using Microsoft.Win32;
namespace ExtraLowLatencyMod
{
/// <summary>
/// Профессиональный оптимизатор системных задержек и задержек ввода Windows NT (Unified Low-Latency Tool)
/// Сборка в один автономный исполняемый (.exe) файл.
/// </summary>
public static class Program
{
// Импорт функции изменения разрешения аппаратного системного таймера
[DllImport("ntdll.dll", SetLastError = true)]
private static extern int NtSetTimerResolution(uint DesiredResolution, bool SetResolution, out uint CurrentResolution);
// Импорт функций консоли для визуального тюнинга
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_HIDE = 0;
private const int SW_SHOW = 5;
[STAThread]
public static void Main(string[] args)
{
// Проверка аргументов командной строки для службы или установщика
if (args.Length > 0)
{
string arg = args[0].ToLower();
if (arg == "--service" || arg == "/service")
{
// Запуск в режиме Windows Service
ServiceBase.Run(new LatencyBackgroundService());
return;
}
if (arg == "--install" || arg == "/install")
{
InstallService();
return;
}
if (arg == "--uninstall" || arg == "/uninstall")
{
UninstallService();
return;
}
}
// Запуск GUI-подобной интерактивной консоли управления
RunInteractiveConsole();
}
private static void RunInteractiveConsole()
{
Console.Title = "ExtraLowLatencyMod - Windows Hardware Latency Suite";
// Проверка присутствия прав Администратора
if (!IsAdministrator())
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[КРИТИЧЕСКИЙ СБОЙ] Для применения твиков ядра нужны права Администратора!");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[РЕШЕНИЕ] Нажмите правой кнопкой мыши по С# EXE и выберите 'Запуск от имени Администратора'.");
Console.ResetColor();
Console.WriteLine("\nНажмите любую клавишу для безопасного выхода...");
Console.ReadKey();
return;
}
while (true)
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(@"
███████╗██╗ ██╗████████╗██████╗ █████╗ ██╗ ██████╗ ██╗ ██╗
██╔════╝╚██╗██╔╝╚══██╔══╝██╔══██╗██╔══██╗██║ ██╔═══██╗██║ ██║
█████╗ ╚███╔╝ ██║ ██████╔╝███████║██║ ██║ ██║██║ █╗ ██║
██╔════╝ ██╔██╗ ██║ ██╔══██╗██╔══██║██║ ██║ ██║██║███╗██║
███████╗██╔╝ ██╗ ██║ ██║ ██║██║ ██║███████╗╚██████╔╝╚███╔███╔╝
╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚══╝╚══╝
");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("=====================================================================");
Console.WriteLine(" СИСТЕМНЫЙ ОПТИМИЗАТОР ЗАДЕРЖЕК ВВОДА И ТАЙМЕРОВ ЯДРА ");
Console.WriteLine("=====================================================================");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[✓] Приложение запущено с административными полномочиями OS.");
Console.ResetColor();
Console.WriteLine("\nВЫБЕРИТЕ ДЕЙСТВИЕ ДЛЯ ОПТИМИЗАЦИИ:");
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("1. Применить комплексные низкозадерживаемые твики (Registry, BCDedit, MMCSS)");
Console.WriteLine("2. Включить аппаратный Message Signaled Interrupts (MSI) режим для всех PCI-устройств");
Console.WriteLine("3. Запустить тайминговый драйвер в текущем окне (фиксация 0.5 мс / 2000 Гц)");
Console.WriteLine("4. Установить тайминговый драйвер как автозапускаемую Windows-службу");
Console.WriteLine("5. Полностью удалить фоновую службу из Windows");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("6. Подробный статус-отчет по текущему таймеру ядра");
Console.WriteLine("0. Выход");
Console.ResetColor();
Console.Write("\nВведите номер пункта > ");
string choice = Console.ReadLine();
switch (choice)
{
case "1":
ApplyGlobalTimerTweaks();
OptimizeScheduler();
ShowReturnPrompt();
break;
case "2":
EnableMSIMode();
ShowReturnPrompt();
break;
case "3":
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("=====================================================================");
Console.WriteLine(" АКТИВАЦИЯ ЯДЕРНОГО ДРАЙВЕРА ВВОДА (0.50 мс - 2000Hz) ");
Console.WriteLine("=====================================================================");
Console.ResetColor();
HoldMaximumResponsiveness();
return;
case "4":
InstallService();
ShowReturnPrompt();
break;
case "5":
UninstallService();
ShowReturnPrompt();
break;
case "6":
ShowTimerDiagnostics();
ShowReturnPrompt();
break;
case "0":
return;
default:
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine("Неизвестный параметр. Попробуйте еще раз.");
Console.ResetColor();
Thread.Sleep(1500);
break;
}
}
}
private static void ShowReturnPrompt()
{
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine("\nНажмите любую клавишу, чтобы вернуться в меню...");
Console.ResetColor();
Console.ReadKey(true);
}
public static void ApplyGlobalTimerTweaks()
{
try
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\n[*] Оптимизация тактовых параметров CPU ядра (BCDEdit)...");
Console.ResetColor();
// Запрет процессору пропускать такты аппаратного таймера
ExecuteCommand("bcdedit", "/set disabledynamictick yes");
// Перевод ядра на аппаратные TSC-такты чистого кремния вместо HPET
ExecuteCommand("bcdedit", "/set useplatformclock no");
ExecuteCommand("bcdedit", "/set tscsyncpolicy Enhanced");
Console.WriteLine(" [+] Параметры DynamicTick и HPET в базе данных конфигурации загрузки настроены.");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[*] Снятие ограничений Windows 11 на запросы разрешения таймера...");
Console.ResetColor();
string kernelPath = @"SYSTEM\CurrentControlSet\Control\Session Manager\kernel";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(kernelPath, true))
{
if (key != null)
{
key.SetValue("GlobalTimerResolutionRequests", 1, RegistryValueKind.DWord);
Console.WriteLine(" [+] Параметр GlobalTimerResolutionRequests установлен в 1 (глобально).");
}
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"[!] Ошибка записи реестра таймера: {ex.Message}");
Console.ResetColor();
}
}
public static void OptimizeScheduler()
{
try
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\n[*] Разблокировка планировщика MMCSS мультимедиа распределения ресурсов...");
Console.ResetColor();
string profilePath = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(profilePath, true))
{
if (key != null)
{
// 0% резерва фоновым процессам - вся мощность активным окнам
key.SetValue("SystemResponsiveness", 0, RegistryValueKind.DWord);
// Отключение сетевого троттлинга карт (исключает пакетирование пинга)
key.SetValue("NetworkThrottlingIndex", unchecked((int)0xFFFFFFFF), RegistryValueKind.DWord);
Console.WriteLine(" [+] Ограничения системного приоритета CPU и Сети сняты.");
}
}
// Перевод дескрипторов задач игр на High
string gamesTaskPath = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile\Tasks\Games";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(gamesTaskPath, true))
{
if (key != null)
{
key.SetValue("GPU Priority", 8, RegistryValueKind.DWord);
key.SetValue("Priority", 6, RegistryValueKind.DWord);
key.SetValue("Scheduling Category", "High", RegistryValueKind.String);
key.SetValue("SFIO Priority", "High", RegistryValueKind.String);
Console.WriteLine(" [+] Категория 'Games' MMCSS переведена на высшие приоритеты.");
}
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"[!] Ошибка твика MMCSS: {ex.Message}");
Console.ResetColor();
}
}
public static void EnableMSIMode()
{
try
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\n[*] Сканирование системной топологии физической шины PCI...");
Console.ResetColor();
string enumPath = @"SYSTEM\CurrentControlSet\Enum\PCI";
using (RegistryKey baseKey = Registry.LocalMachine.OpenSubKey(enumPath, true))
{
if (baseKey == null)
{
Console.WriteLine(" [!] Устройства PCI шины не обнаружены в текущем улье реестра.");
return;
}
int matches = 0;
foreach (string deviceId in baseKey.GetSubKeyNames())
{
using (RegistryKey devInstance = baseKey.OpenSubKey(deviceId, true))
{
if (devInstance == null) continue;
foreach (string subId in devInstance.GetSubKeyNames())
{
string devicePath = subId + @"\Device Parameters";
using (RegistryKey configKey = devInstance.OpenSubKey(devicePath, true))
{
if (configKey == null) continue;
using (RegistryKey msiKey = configKey.CreateSubKey(@"Interrupt Management\MessageSignaledInterruptProperties"))
{
if (msiKey != null)
{
// Активируем MSI
msiKey.SetValue("MSISupported", 1, RegistryValueKind.DWord);
// Запросы обрабатываются в один выделенный и быстрый вектор прерывания ядра
msiKey.SetValue("MessageNumberLimit", 1, RegistryValueKind.DWord);
matches++;
}
}
}
}
}
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"[✓] Аппаратные прерывания MSI и приоритеты успешно включены для {matches} PCI-чипов!");
Console.ResetColor();
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"[!] Ошибка MSI оптимизации: {ex.Message}");
Console.ResetColor();
}
}
public static void HoldMaximumResponsiveness()
{
uint desired = 5000; // 0.5 мс
uint current;
int result = NtSetTimerResolution(desired, true, out current);
if (result == 0)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"[АКТИВНО] Удержание осуществлено! Текущее разрешение Windows: {current / 10000.0:F4} мс.");
Console.WriteLine("[СТАТУС] Микро-джиттер равен нулю. Частота тиков ядра зафиксирована на 2000 Гц.");
Console.ResetColor();
Console.WriteLine("\nДля сброса таймера в дефолт и выхода зажмите сочетание [Ctrl + C].");
// Закрепление потока без создания нагрузки на CPU циклы
Thread.Sleep(Timeout.Infinite);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"[!] Ошибка вызова ntdll. NtSetTimerResolution вернул код сбоя: {result}");
Console.ResetColor();
}
}
private static void ShowTimerDiagnostics()
{
uint current;
// Считываем текущее разрешение отправкой ложного SetResolution=false
int result = NtSetTimerResolution(5000, false, out current);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\n================ ДИАГНОСТИКА ТАЙМЕРОВ ЯДРА ================");
Console.ResetColor();
Console.WriteLine($"Код опроса ntdll.dll: {result}");
Console.WriteLine($"Текущий шаг прерывания Windows: {current / 10000.0:F4} мс");
Console.WriteLine($"Приблизительная плотность кадров ввода: {(1000.0 / (current / 10000.0)):F1} Гц");
if (current <= 5500)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Вердикт: Идеально. Включен Low-Latency режим (0.50 мс - 0.55 мс).");
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Вердикт: Требуется включение. Система работает на рваном таймере планировщика (~15.6 мс).");
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("===========================================================");
Console.ResetColor();
}
private static void InstallService()
{
try
{
string exePath = Process.GetCurrentProcess().MainModule.FileName;
Console.WriteLine($"[*] Установка службы ExtraLowLatencyMod...");
// Используем стандартную sc.exe утилиту Windows для регистрации службы
ExecuteCommand("sc", $"create ExtraLowLatencyModService binPath= \"\\\"{exePath}\\\" --service\" start= auto displayname= \"ExtraLowLatencyMod Kernel Keeper\"");
ExecuteCommand("sc", "description ExtraLowLatencyModService \"Удерживает разрешение глобального таймера Windows на 0.5 мс (2000 Гц) для полной ликвидации Input Lag.\"");
ExecuteCommand("sc", "start ExtraLowLatencyModService");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[✓] Фоновая служба успешно создана, добавлена в автозапуск Windows и запущена!");
Console.ResetColor();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"[!] Сбой инсталляции службы: {ex.Message}");
Console.ResetColor();
}
}
private static void UninstallService()
{
try
{
Console.WriteLine("[*] Остановка и удаление Windows Service...");
ExecuteCommand("sc", "stop ExtraLowLatencyModService");
ExecuteCommand("sc", "delete ExtraLowLatencyModService");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[✓] Служба ExtraLowLatencyModService успешно полностью удалена из системных ресурсов.");
Console.ResetColor();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"[!] Сбой удаления службы: {ex.Message}");
Console.ResetColor();
}
}
private static void ExecuteCommand(string fileName, string arguments)
{
try
{
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (Process p = Process.Start(psi))
{
p.WaitForExit();
}
}
catch { }
}
private static bool IsAdministrator()
{
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
}
/// <summary>
/// Манифест класса службы для бесконфликтной интеграции Windows Service в один .exe
/// </summary>
public class LatencyBackgroundService : ServiceBase
{
private Thread _timerThread;
private bool _isRunning;
[DllImport("ntdll.dll", SetLastError = true)]
private static extern int NtSetTimerResolution(uint DesiredResolution, bool SetResolution, out uint CurrentResolution);
public LatencyBackgroundService()
{
this.ServiceName = "ExtraLowLatencyModService";
this.CanStop = true;
this.AutoLog = true;
}
protected override void OnStart(string[] args)
{
_isRunning = true;
_timerThread = new Thread(HoldLoop)
{
IsBackground = true,
Priority = ThreadPriority.Lowest
};
_timerThread.Start();
}
private void HoldLoop()
{
uint desired = 5000; // 0.5 мс
uint current;
while (_isRunning)
{
// Посылаем запрос в ntdll
NtSetTimerResolution(desired, true, out current);
// Засыпаем на 30 секунд. Вызов удерживается, пока активна служба
Thread.Sleep(30000);
}
}
protected override void OnStop()
{
_isRunning = false;
uint current;
// Сбрасываем таймер в дефолт перед выгрузкой службы
NtSetTimerResolution(5000, false, out current);
}
}
}