Calculate Thread.Sleep() for bitrate limit

146 views Asked by At

I have a class reading a http stream file.

    static  long CurrentMilliseconds { get { return Environment.TickCount; } }
    public void ReadFile()
    {
        ...
        while(true)
        {
            int r = stm.Read(buf, 0, bufSize);
            if(r == 0) break;
            ...
            int x= CalculateDelay()
            Thread.Sleep(x);
        }
    }

Let's say I download 5 files in parallel (5 instances of this class running) and I want total bitrate<800 kb/s

I have difficulty calculating delay x. Any help appreciated.

1

There are 1 answers

0
usr On
double downloadDurationInSec = ...; //provide this
long bytesTransferred = ...; //provide this
double targetBytesPerSec = 800 * 1000;
double targetDurationInSec = bytesTransferred / targetBytesPerSec;
if (targetDurationInSec < downloadDurationInSec) {
 double sleepTimeInSec = downloadDurationInSec - targetDurationInSec;
 Thread.Sleep(TimeSpan.FromSeconds(sleepTimeInSec));
}

Note the expressive variable naming which includes the units.

The idea of the algorithm is to calculate how long the download should have taken up to the current point. If it was faster than it should have, sleep the difference.

This is numerically stable because you don't incrementally update any variables.