Answer the question
In order to leave comments, you need to log in
Get the average value per second. How to do it more correctly?
Hello. I need to calculate the average of 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;
}
}
}
}
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("Частота обновления: {0}/сек. ", monitor.Frequency);
Thread.Sleep(1000);
}
}),
};
Array.ForEach(tasks, task => task.Start());
Task.WaitAll(tasks);
Console.WriteLine("Конец.");
Console.ReadKey();
}
}
}
Answer the question
In order to leave comments, you need to log in
On mobile, hard to see. There are two options for calculating the frequency.
1 for the last second, count the frequency, hold the queue, delete what lives longer than 1 second, add new ticks, recalculate the frequency, this is the length of the queue. Option 2 is more difficult. The same, but at different time intervals (less than 1 sec in terms of 1 sec), if necessary.
For example 2 events in 200 ms, that's 10 events in 1 second. Everything is abstract.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question