I’m working on an ASP.NET web service application which makes heavy use of CPU. I’ve noticed on a 4 core server, the CPU is underutilized. So I’ve come up with a simple service to see if it is possible to reach 100% CPU. Here it is.
The calling client attacks this server with concurrent threads and repeated messages. Each request takes between 0.5 and 2 seconds to complete (depending on # of threads). The highest CPU usage it reaches is 80% across all 4 cores. I get the same result if I use 4 threads or 16 threads, 1 client or 2 clients. A 2 core box has the same problem.
So, is it possible to reach 100% CPU on a multi-core IIS server with code that isn’t in an endless loop?
public class MyHttpHandler : IHttpHandler
{
public bool IsReusable { get { return true; } }
public void ProcessRequest( HttpContext context )
{
switch( context.Request.HttpMethod )
{
case "GET":
{
string s = "";
for( int i = 0; i < 999999; ++i )
{
s = s.Substring( s.Length / 2 );
s += i.ToString();
}
context.Response.Output.WriteLine( "<html><body><h1>Web Service - " + s + "</h1></body></html>" );
context.Response.StatusCode = 200;
break;
}
default:
{
context.Response.StatusCode = 405;
break;
}
}
}
}
You are generating garbage at full speed. This triggers lots of GCs. Before and after a GC can happen, for a brief duration all threads must be stopped. This is preventing the process from saturating the CPU.
Put in an arithmetic loop.
Thread.SpinWaitdoes not guarantee CPU usage because internally it asks Windows to deschedule the current thread. It is not a simple “infinite” loop.