# To obtain a mean value per second. How to do it more correctly?

Hello. I need to calculate the average value of the received data per second.
For example, there is a class:

``````class StateMonitor
{
private long _quantityOfValues;
private long _quantityOfCalls;

private readonly object _quantityOfValuesSync = new object();
private readonly object _frequencySync = new object();

public void Increment()
{
lock (_quantityOfValuesSync)
{
_quantityOfValues++;
}
}

public int Frequency
{
get
{
long quantityOfValues;
lock (_quantityOfValuesSync)
{
quantityOfValues = _quantityOfValues;
}

lock (_frequencySync)
{
double result = (double)quantityOfValues / ++_quantityOfCalls;
result = Math.Round(result, MidpointRounding.AwayFromZero);
return (int)result;
}
}
}
}``````

He correctly believed the frequency of a method call Increment per second need to call a property Frequency 1 time per second. That not convenient to use and reliable. Surely there is a formula for such a calculation. Guess will need to keep the time Frequency properties in order to correctly count. Chet did not depetro, how to count?

Here is the code for the test class above:
``````using System;

namespace FrequencyReceivingTest2
{
internal class Program
{
#region Entry point

private static Program _program;

private static void Main(string[] args)
{
_program = new Program();
_program.Run(args);
}

#endregion

private void Run(string[] args)
{
var monitor = new StateMonitor();
int counter = 0;

{
{
while (counter++ < 20)
{
int ms = 0;
while (ms < 1000)
{
const int WaitMs = 200;
monitor.Increment();
ms += WaitMs;
}
}
}),

{
while (counter < 20)
{
Console.WriteLine("rate: {0}/sec. ", monitor.Frequency);
}
}),
};

Console.WriteLine("The End.");
}
}
}``````
July 9th 19 at 13:12