Skip to content

Instantly share code, notes, and snippets.

@joshuamkite
Created July 12, 2023 10:53
Show Gist options
  • Save joshuamkite/16ad473caddb46ce917983dcbd3ae98b to your computer and use it in GitHub Desktop.
Save joshuamkite/16ad473caddb46ce917983dcbd3ae98b to your computer and use it in GitHub Desktop.
CPU stress test ChatGPT
The reason your script isn't functioning as expected is that the `start-job` cmdlet spins off a new background job for each logical processor on your machine. However, there's no wait command for these jobs to finish, and thus the script just runs to completion without waiting for these CPU-intensive tasks to finish. Then it calls `Stop-Job *`, which kills any running background jobs, likely before they've had a chance to start.
Moreover, the nested loops in your script are potentially creating an exceedingly large number of iterations. If you're trying to generate CPU load, you don't need that much looping; a smaller, but still large, number of iterations would be sufficient.
Also, keep in mind that your jobs are using the same variable names for their loop counters (`$loopnumber` and `$loopnumber1`). This might not cause an issue, but it can lead to confusion and potential bugs. It's a best practice to use unique, descriptive variable names.
Here's an example of how you could revise your script:
```powershell
$NumberOfLogicalProcessors = Get-WmiObject win32_processor | Select-Object -ExpandProperty NumberOfLogicalProcessors
$jobs = @()
ForEach ($core in 1..$NumberOfLogicalProcessors){
$jobs += Start-Job -ScriptBlock{
$result = 1
for ($i=0; $i -lt 100000000; $i++){
$result *= $i
if ($i % 10000 -eq 0) { $result = 1 } # Reset result every 10000 iterations to avoid overflow
}
}
}
# Wait for all jobs to complete
$jobs | Wait-Job
# Clean up jobs
$jobs | Remove-Job
Read-Host "Press any key to exit..."
```
This script will create a job for each logical processor, each of which will run a loop 100,000,000 times, multiplying a running total by the loop counter. The running total is reset every 10,000 iterations to prevent it from becoming too large and causing an overflow. The `Wait-Job` cmdlet is used to wait for all jobs to complete before proceeding, and the `Remove-Job` cmdlet is used to clean up the jobs after they're done.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment