Skip to content

Instantly share code, notes, and snippets.

@Tapped
Last active September 8, 2016 13:02
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 Tapped/b4c0df072b2ff6fd38c6c4aff55d4669 to your computer and use it in GitHub Desktop.
Save Tapped/b4c0df072b2ff6fd38c6c4aff55d4669 to your computer and use it in GitHub Desktop.
Mono Sleep Performance Test
using System;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Reflection;
namespace TestSleep
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine (GetMonoVersion ());
Console.WriteLine ("Sleep performance test. Press enter to exit.");
using(var performanceCounter = new PerformanceCounter ("Process", "% Processor Time", GetInstanceName(Process.GetCurrentProcess()), false))
using(var ctSource = new CancellationTokenSource ())
{
var thread = new Thread (RunWithSleep)
{
Name = "Dummy Sleep Thread"
};
thread.Start (ctSource.Token);
var readLine = Task.Run (() => Console.ReadLine());
while (!readLine.IsCompleted)
{
Console.Write("\rCPU Time: " + performanceCounter.NextValue() + "%");
Thread.Sleep(TimeSpan.FromSeconds(1));
}
ctSource.Cancel ();
thread.Join ();
}
}
/**
* This Thread starts to sleep for one millisecond continously
* and cause high CPU usage in Mono version >= 4.4.
*/
static void RunWithSleep(object cancellationToken)
{
Console.WriteLine ("Starting 'Dummy Sleep Thread'");
var cancel = (CancellationToken)cancellationToken;
while(!cancel.IsCancellationRequested)
{
Thread.Sleep(1);
}
Console.WriteLine ("'Dummy Sleep Thread' done");
}
static string GetInstanceName(Process process)
{
PerformanceCounterCategory processCategory = new PerformanceCounterCategory("Process");
string[] instanceNames = processCategory.GetInstanceNames();
foreach (string name in instanceNames)
{
if (name.StartsWith(process.Id.ToString()))
{
return name;
}
}
throw new Exception ("Failed to find instance name");
}
static string GetMonoVersion()
{
Type type = Type.GetType("Mono.Runtime");
if (type != null)
{
MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
if (displayName != null)
return displayName.Invoke (null, null).ToString();
}
return "Unknown Version";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment