Created
February 9, 2021 23:04
-
-
Save pearswj/27ce6921eac6a60850140846082296bf to your computer and use it in GitHub Desktop.
.NET process affinity test
This file contains hidden or 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
using System; | |
using System.Diagnostics; | |
using System.Threading; | |
namespace procaff | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("Hello World!"); | |
// only use first logical processor for this process | |
Process proc = Process.GetCurrentProcess(); | |
ProcessThread thread = proc.Threads[0]; | |
thread.IdealProcessor = 0; | |
thread.ProcessorAffinity = (IntPtr)1; | |
Console.WriteLine(Environment.ProcessorCount); | |
ConsumeCPU(90); | |
} | |
// https://stackoverflow.com/a/2514697 | |
public static void ConsumeCPU(int percentage) | |
{ | |
if (percentage < 0 || percentage > 100) | |
throw new ArgumentException("percentage"); | |
Stopwatch watch = new Stopwatch(); | |
watch.Start(); | |
while (true) | |
{ | |
// make the loop go on for "percentage" milliseconds then sleep the remaining | |
// percentage milliseconds. So 40% utilization means work 40ms and sleep 60ms | |
if (watch.ElapsedMilliseconds > percentage) | |
{ | |
Thread.Sleep(100 - percentage); | |
watch.Reset(); | |
watch.Start(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment