你会如何​​限制每秒操作数? [英] How would you limit the number of operations per second?

查看:138
本文介绍了你会如何​​限制每秒操作数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你会如何限制每秒操作数?

How would you limit the number of operations per second?

可以说,我们已经从一个位置复制文件到另一个,我们不希望超过5个文件,以每秒处理。

Lets say we have to copy files from one location to another and we don't want more than 5 files to be processed per second.

请看看我在做什么。

private static string currentStamp;
private static int processedInCurrentStamp = 0;

private static void Main(string[] args)
{
    currentStamp = DateTime.Now.ToString("{0:d/M/yyyy HH:mm:ss}");
    Run();
}

private static void Run()
{
    for (int i = 0; i < Int32.MaxValue; i++)
    {
        string s = DateTime.Now.ToString("{0:d/M/yyyy HH:mm:ss}");
        if (currentStamp.Equals(s))
        {
            if (processedInCurrentStamp < 5)
            {
                ProcessItem();
                processedInCurrentStamp++;
            }
        }
        else
        {
            Console.WriteLine("{0} ::: {1}", currentStamp, processedInCurrentStamp);
            currentStamp = s;
            processedInCurrentStamp = 0;
        }
    }
}

但我需要一个更优雅和防弹的方式。

But I need a more elegant and bullet proof way.

推荐答案

获取的开始时间,然后在循环计算出应处理到当前时间的文件的最大数量,和睡眠如果你超前:

Get the starting time, and then in the loop calculate the maximum number of files that should be processed up to the current time, and sleep if you are ahead:

DateTime start = DateTime.UtcNow;

int i = 1;
while (i <= 100) {

  int limit = (int)((DateTime.UtcNow - start).TotalSeconds * 5.0);

  if (i <= limit) {

    Console.WriteLine(i);
    i++;

  } else {
    Thread.Sleep(100);
  }

}

这样,code将赶上,如果某些操作需要更长的时间。如果你只得到三个操作的一个第二,它可以做七下一秒。

This way the code will catch up if some operations take longer. If you only get three operations one second, it can do seven the next second.

请注意,我用 UtcNow 而不是现在,以避免讨厌的跳跃在时间上一年发生两次

Note that I am using UtcNow instead of Now to avoid the nasty jump in time that happens twice a year.

另一种方法是测量一个操作需要的时间,睡它的其余部分的时间段:

Another alternative is to measure the time that an operation takes, and sleep the rest of it's time slot:

for (int i = 1; i <= 100; i++ ) {

  DateTime start = DateTime.UtcNow;

  Console.WriteLine(i);

  int left = (int)(start.AddSeconds(1.0 / 5.0) - DateTime.UtcNow).TotalMilliseconds;
  if (left > 0) {
    Thread.Sleep(left);
  }

}

这篇关于你会如何​​限制每秒操作数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆