Skip to content

Instantly share code, notes, and snippets.

@pearswj
Created February 9, 2021 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pearswj/27ce6921eac6a60850140846082296bf to your computer and use it in GitHub Desktop.
Save pearswj/27ce6921eac6a60850140846082296bf to your computer and use it in GitHub Desktop.
.NET process affinity test
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