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;
using System.Threading;
using System.Threading.Tasks;

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;

 Task[] tasks =
{
 new Task(() =>
{
 while (counter++ < 20)
{
 int ms = 0;
 while (ms < 1000)
{
 const int WaitMs = 200;
monitor.Increment();
Thread.Sleep(WaitMs);
 ms += WaitMs;
}
}
}),

 new Task(() =>
{
 while (counter < 20)
{
 Console.WriteLine("rate: {0}/sec. ", monitor.Frequency);
Thread.Sleep(1000);
}
}),
};

 Array.ForEach(tasks, task => task.Start());

Task.WaitAll(tasks);
Console.WriteLine("The End.");
Console.ReadKey();
}
}
}
July 9th 19 at 13:12
2 answers
July 9th 19 at 13:14
With mobile phones , uncomfortable to watch. There are two ways of counting frequency.
1 in the last second to consider the frequency, keep the queue, and remove that 1 sec longer lives,add a new tick, counts the frequency, is the length of the queue. Option 2 is more complicated. The same thing, but at different periods of time(less than 1 sec in terms of for 1 sec) if necessary.
For example 2 events 200 MS, is 10 events in 1 sec. Abstract described.
July 9th 19 at 13:16
Save the timestamp of the first and last call Increment. The number of calls per second is easily calculated on demand: quantityOfValues/(tend-tbegin). (tend-tbegin), of course, need to convert to seconds.
This is the average frequency for the entire period. - mercedes commented on July 9th 19 at 13:19

Find more questions by tags C#MathematicsProgramming