Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating CPU usage

Our business model requires to charge users based on CPU hours/usage.

Initially I was thinking about simply using StopWatch and then use elapsed time as a unit of measure.

But the problem I see with this approach is that in the day time when 5000 users are hitting the server, the elapsed time for the same piece of code will be higher than in the night time when only 50 users are hitting the server.

Other option is to charge users based on the iterations performed on the data users passed in. There are couple of issues with this approach as well.

  • Some functions would not require any iteration over data.
  • CPU usage for x + y is lower than that of x + y * z.

What is a good way to calculate CPU usage information in C#/.Net so that it remains the same for all users for the same operation regardless of the server's load?

Possibly, total amount of actual assembly level instructions? Is there a way to get that information in C#?

What other approached, recommendations can you share?

Thanks a lot for looking into this.

like image 849
Moon Avatar asked Jun 10 '12 15:06

Moon


1 Answers

Execute whatever your users want to run in a separate process and look for its CPU time after the process is done. This is also different from wallclock time as it only takes into account the time the process actually ran on the CPU.

Minimal example for those who are unwilling to read documentation:

ProcessStartInfo psi = new ProcessStartInfo(@"C:\Blah\Foo.exe");
Process p = Process.Start(psi);
p.WaitForExit();
TimeSpan time = p.TotalProcessorTime;
p.Close();

You may want to run this asynchronously, though.

No need for estimation, guessing or black magic. You cannot calculate it reliably anyway.

like image 111
Joey Avatar answered Oct 15 '22 05:10

Joey