Chris C.
Chris C.

Reputation: 1001

Trying to reach 100% CPU utilization in IIS and ASP.NET

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;
            }
        }
    }
}

Upvotes: 3

Views: 2168

Answers (2)

usr
usr

Reputation: 171246

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.SpinWait does not guarantee CPU usage because internally it asks Windows to deschedule the current thread. It is not a simple "infinite" loop.

Upvotes: 4

Mike Atlas
Mike Atlas

Reputation: 8241

You can put the thread into a SpinWait for a very large number of iterations. This isn't an endless loop but it does run for a long time, probably.

Thread.SpinWait(Int32.MaxValue);

Upvotes: 1

Related Questions