Last active
September 8, 2023 07:33
-
-
Save roy4801/833ba38d3f8caa4793f4f215c3fab407 to your computer and use it in GitHub Desktop.
Limit CPU usage >= Windows 8 (JOBOBJECT_CPU_RATE_CONTROL_INFORMATION)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
HANDLE hJob = CreateJobObject( NULL, NULL ); | |
JOBOBJECT_CPU_RATE_CONTROL_INFORMATION cpuRateControlInformation; | |
ZeroMemory( &cpuRateControlInformation, sizeof( cpuRateControlInformation ) ); | |
int cpuUsagePercent = 30; | |
cpuRateControlInformation.CpuRate = cpuUsagePercent * 100; | |
cpuRateControlInformation.ControlFlags = JOB_OBJECT_CPU_RATE_CONTROL_ENABLE | JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP; | |
if ( !SetInformationJobObject( hJob, JobObjectCpuRateControlInformation, &cpuRateControlInformation, sizeof( cpuRateControlInformation ) ) ) | |
{ | |
printf( "SetInformationJobObject failed (%d)\n", GetLastError() ); | |
return 1; | |
} | |
if ( !AssignProcessToJobObject( hJob, GetCurrentProcess() ) ) | |
{ | |
printf( "AssignProcessToJobObject failed (%d)\n", GetLastError() ); | |
return 1; | |
} | |
BOOL bInJob = FALSE; | |
IsProcessInJob( GetCurrentProcess(), NULL, &bInJob ); | |
if ( bInJob ) | |
{ | |
printf( "Process is in Job!\n" ); | |
} | |
// make cpu load | |
for ( int i = 0; i < 20; i++ ) | |
{ | |
std::thread( []() -> void { | |
while ( 1 ) | |
{ | |
clock_t wakeup = clock() + 50; | |
while ( clock() < wakeup ) {} | |
Sleep( 50 ); | |
} | |
} ).detach(); | |
} | |
(void)getchar(); | |
CloseHandle( hJob ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment