Question

I have a lengthy method that writes data into a database. It is called repeatedly. I also maintain the counter of records written so far, as well as the total number of records that need to be written as such:

private int currentCount;
private int totalCount;
private double fAverageTransferRate;

bool processingMethod()
{
    //Processes one record at a time

    DateTime dtNow = DateTime.Now;   //Time now

    fAverageTransferRate = //?
}

I know that to calculate a transfer rate I need to take the number of records written in one second, right, but here come two questions:

  1. How would I time my calculation exactly at 1 second mark?

  2. And, most of all, how do I calculate an average transfer rate?

PS. I need this done, on the go, so to speak, while this method is running (and not after it is finished.)

Was it helpful?

Solution

You could think about it a different way, since what you're really interested in is the rate of processing records. Therefore, you con't need to make the calculation happen at precisely 1 second intervals. Rather, you need it happen about every second but then know exactly when it happens.

To calculate the average transfer rate, just keep a running count of the number of records you are transferring. If more than 1 second has elapsed since the last time you computed the average, its time to compute the average anew. Zero out the running count when you're done, in preparation for the next round.

Pseudo-code follows:

// somewhere outside: 
int lastdonetime = 0;
int numprocessed = 0;

bool processingMethod()
{
    DateTime dtNow = DateTime.Now;   //Time now
    if (lastdonetime == 0) lastdonetime = dtNow;
    if (dtNow - lastdonetime > 1) {
       fAverageTransferRate = numprocessed / (dtNow - lastdonetime);
       // Do what you want with fAverageTransferRate
       lastdonetime = dtNow;
       numprocessed = 0;
    }
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top