2

我有一个方法 Limit() 计算在特定时间通过某个通道的带宽,并通过使用 Thread.Sleep() 来限制它(如果达到带宽限制)。方法本身产生正确的(在我看来结果)但 Thread.Sleep 没有(由于多线程 CPU 使用),因为我有正确的“毫秒ToWait”,但之后的速度检查远非我通过的限制。

有没有办法让限制更精确?

限制器类

    private readonly int m_maxSpeedInKbps;
    public Limiter(int maxSpeedInKbps)
    {
        m_maxSpeedInKbps = maxSpeedInKbps;
    }

    public int Limit(DateTime startOfCycleDateTime, long writtenInBytes)
    {
        if (m_maxSpeedInKbps > 0)
        {
            double totalMilliseconds = DateTime.Now.Subtract(startOfCycleDateTime).TotalMilliseconds;
            int currentSpeedInKbps = (int)((writtenInBytes / totalMilliseconds));
            if (currentSpeedInKbps - m_maxSpeedInKbps > 0)
            {
                double delta = (double)currentSpeedInKbps / m_maxSpeedInKbps;
                int millisecondsToWait = (int)((totalMilliseconds * delta) - totalMilliseconds);
                if (millisecondsToWait > 0)
                {
                    Thread.Sleep(millisecondsToWait);
                    return millisecondsToWait;
                }
            }
        }

        return 0;
    }

在大增量中总是失败的测试类

[TestMethod]
public void ATest()
{
    List<File> files = new List<File>();
    for (int i = 0; i < 1; i++)
    {
        files.Add(new File(i + 1, 100));
    }

    const int maxSpeedInKbps = 1024; // 1MBps
    Limiter limiter = new Limiter(maxSpeedInKbps);

    DateTime startDateTime = DateTime.Now;
    Parallel.ForEach(files, new ParallelOptions {MaxDegreeOfParallelism = 5}, file =>
    {
        DateTime currentFileStartTime = DateTime.Now;
        Thread.Sleep(5);
        limiter.Limit(currentFileStartTime, file.Blocks * Block.Size);
    });

    long roundOfWriteInKB = (files.Sum(i => i.Blocks.Count) * Block.Size) / 1024;
    int currentSpeedInKbps = (int) (roundOfWriteInKB/DateTime.Now.Subtract(startDateTime).TotalMilliseconds*1000);

    Assert.AreEqual(maxSpeedInKbps, currentSpeedInKbps, string.Format("maxSpeedInKbps {0} currentSpeedInKbps {1}", maxSpeedInKbps, currentSpeedInKbps));
} 
4

2 回答 2

3

Thread.Sleep在我发现waithandles之前,我曾经使用过很多。使用等待句柄,您可以暂停线程,当等待句柄从其他地方触发或达到时间阈值时,线程将再次激活。也许可以重新设计您的限制方法以以某种方式使用等待句柄,因为在很多情况下它们确实比Thread.Sleep

于 2013-05-26T12:42:53.933 回答
3

您可以使用繁忙的等待相当准确地完成此操作,但我不推荐它。您应该使用其中一个多媒体计时器来等待。

但是,此方法将相当准确地等待:

void accurateWait(int millisecs)
{
    var sw = Stopwatch.StartNew();

    if (millisecs >= 100)
        Thread.Sleep(millisecs - 50);

    while (sw.ElapsedMilliseconds < millisecs)
        ;
}

但这是一个繁忙的等待,会非常消耗 CPU 周期。它也可能受到垃圾收集或任务重新调度的影响。

这是测试程序:

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading;

namespace Demo
{
    class Program
    {
        void run()
        {
            for (int i = 1; i < 10; ++i)
                test(i);

            for (int i = 10; i < 100; i += 5)
                test(i);

            for (int i = 100; i < 200; i += 10)
                test(i);

            for (int i = 200; i < 500; i += 20)
                test(i);
        }

        void test(int millisecs)
        {
            var sw = Stopwatch.StartNew();
            accurateWait(millisecs);
            Console.WriteLine("Requested wait = " + millisecs + ", actual wait = " + sw.ElapsedMilliseconds);
        }

        void accurateWait(int millisecs)
        {
            var sw = Stopwatch.StartNew();

            if (millisecs >= 100)
                Thread.Sleep(millisecs - 50);

            while (sw.ElapsedMilliseconds < millisecs)
                ;
        }

        static void Main()
        {
            new Program().run();
        }
    }
}
于 2013-05-26T13:35:02.177 回答