0

Are CounterSample instances returned from PerformanceCounter.NextSample() configurable? Can I configure the counter and sampling e.g. to query instant values 5 times a minute and give me an average for 5 minutes? How is the sampling determined?

Here is an example of the Processor/% Processor Time for _Total

var procProcTime = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);

var sample = procProcTime.NextSample();
do
{
    await Task.Delay(_delay5Minutes);

    var newSample = procProcTime.NextSample();    
    var avg5Minutes = CounterSample.Calculate(sample, newSample);
}
while (!token.IsCancellationRequested);

Trying to reverse engineer the docs is painful. Since the CounterSample has readonly properties, it looks like the counter provider (in this example, Processor/% Processor Time) predetermines the sampling?

These docs are amazingly full but amazingly difficult to understand.

pomeroy
  • 1,377
  • 1
  • 12
  • 21
  • Why not just use `NextValue()` and call it once every 5 minutes? `NextValue` is already doing the average calculation for you from the previous call. – Scott Chamberlain Feb 17 '17 at 21:46
  • Does `NextValue()` actually do averaging since the last call? That doesn't sound right... I think it gives an instantaneous value. – pomeroy Feb 17 '17 at 22:14
  • 3
    No it does not, one of the more common questions on this site is "Why does `.NextValue()` only give me `0` or `100` when I call it for `% Processor Time`", and the answer is "Because .NextValue() is the average processor time between the last two calls, on the very first call the only thing it can tell you is "[During this current timeslice did the processor execute code" and the only answers it can give are 0 (no) or 100 (yes)", you must call the function once and wait at least 100ms (the size of a timeslice) to get accurate results](http://stackoverflow.com/questions/8462331/#8462977)" – Scott Chamberlain Feb 17 '17 at 22:31
  • Ok, that's right, but what is the sampling? Surely it's not just two instantaneous measurements, right? – pomeroy Feb 18 '17 at 02:20
  • 1
    The sampling is 100ms (I can't remember where I found that number). the way it works is (I think) it gets the cpu executed instruction count for the start point and the end point, then it has the maximum theoretical it could be between those two points, then it does `actual count / theoretical max` and that result is the processor %. – Scott Chamberlain Feb 18 '17 at 03:34

0 Answers0