代码之家  ›  专栏  ›  技术社区  ›  Richard Knop

限制每个时间单位的迭代次数

c++
  •  1
  • Richard Knop  · 技术社区  · 15 年前

    有没有办法限制每个时间单位的迭代次数?例如,我有一个这样的循环:

    for (int i = 0; i < 100000; i++)
    {
        // do stuff
    }
    

    我想限制上面的循环,这样每秒最多有30次迭代。

    我还希望迭代在时间轴上均匀定位,这样就不会像前0.4s中的30次迭代,然后等待0.6s。

    有可能吗?它不必完全精确(尽管越精确越好)。

    6 回复  |  直到 15 年前
        1
  •  8
  •   toddw    15 年前

        2
  •  2
  •   ruslik    15 年前

    Now() GetTickCount()

     for (int i = 0; i < 1000; i++){
         DWORD have_to_sleep_until = GetTickCount() + EXPECTED_ITERATION_TIME_MS;
         // do stuff
         Sleep(max(0, have_to_sleep_until - GetTickCount()));
    };
    
        3
  •  1
  •   Hongseok Yoon    15 年前

        4
  •  1
  •   g19fanatic    15 年前

    QueryPerformanceCounter()

    QueryPerformanceFrequency(&freq)
    timeWanted = 1.0/30.0   //time per iteration if 30 iterations / sec
    for i
        QueryPerf(count1)
        do stuff
        queryPerf(count2)
        timeElapsed = (double)(c2 - c1) * (double)(1e3) / double(freq)  //time in milliseconds
        timeDiff = timeWanted - timeElapsed
        if (timeDiff > 0) 
            QueryPerf(c3)
            QueryPerf(c4) 
            while ((double)(c4 - c3) * (double)(1e3) / double(freq) < timeDiff)
                queryPerf(c4)
    end for
    

        5
  •  1
  •   riderchap    15 年前

        6
  •  0
  •   Albert Wang    15 年前