0

我尝试使用 usleep 确保每个循环的执行时间为 10 毫秒,但有时会超过 10 毫秒。

我不知道如何解决这个问题,在这种情况下使用usleepgettimeofday是否合适?

请帮助我找出我错过了什么。

结果:0.0127289 0.0136499 0.0151598 0.0114031 0.014801

double tvsecf(){
     struct timeval tv;
     double asec;

     gettimeofday(&tv,NULL);
     asec = tv.tv_usec;
     asec /= 1e6;
     asec += tv.tv_sec;

     return asec;
}
int main(){
    double t1 ,t2;
    t1 = tvsecf();
    for(;;){
        t2= tvsecf();
        if(t2-t1 >= 0.01){
            if(t2-t1 >= 0.011)
                cout << t2-t1 <<endl;
            t1 = tvsecf();
        }
        usleep(100);
    }
}
4

3 回答 3

3

为了防止循环开销(通常是未知的)不断累积错误,您可以休眠一个时间,而不是一个持续时间。使用 C++<chrono><thread>库,这非常容易:

#include <chrono>
#include <iostream>
#include <thread>

int
main()
{
    using namespace std;
    using namespace std::chrono;
    auto t0 = steady_clock::now() + 10ms;
    for (;;)
    {
        this_thread::sleep_until(t0);
        t0 += 10ms;
    }
}

steady_clock::now()为了确定迭代之间的时间,也许更重要的是,平均迭代时间可以用更多的调用来修饰它:

#include <chrono>
#include <iostream>
#include <thread>

int
main()
{
    using namespace std;
    using namespace std::chrono;
    using dsec = duration<double>;
    auto t0 = steady_clock::now() + 10ms;
    auto t1 = steady_clock::now();
    auto t2 = t1;
    constexpr auto N = 1000;
    dsec avg{0};
    for (auto i = 0; i < N; ++i)
    {
        this_thread::sleep_until(t0);
        t0 += 10ms;
        t2 = steady_clock::now();
        dsec delta = t2-t1;
        std::cout << delta.count() << "s\n";
        avg += delta;
        t1 = t2;
    }
    avg /= N;
    cout << "avg = " << avg.count() << "s\n";
}

上面我通过在循环中做更多的事情来增加循环开销。然而,循环仍然会每10毫秒唤醒一次。有时操作系统会延迟唤醒线程,但下一次循环会自动调整自己休眠更短的时间。因此,平均迭代率自校正到 10 毫秒。

在我的机器上,这只是输出:

...
0.0102046s
0.0128338s
0.00700504s
0.0116826s
0.00785826s
0.0107023s
0.00912614s
0.0104725s
0.010489s
0.0112545s
0.00906409s
avg = 0.0100014s
于 2018-06-28T18:48:57.390 回答
0

usleep 手册页

任何系统活动或处理调用所花费的时间或系统计时器的粒度都可能会稍微延长睡眠时间。

如果您需要高分辨率:在 Unix(或 Linux)上使用 C 查看此答案,该答案解释了如何使用 clock_gettime 使用高分辨率计时器。

编辑:正如 Tobias nanosleep所述,可能是一个更好的选择:

Compared to sleep(3) and usleep(3), nanosleep() has the following
advantages: it provides a higher resolution for specifying the sleep
interval; POSIX.1 explicitly specifies that it does not interact with
signals; and it makes the task of resuming a sleep that has been
interrupted by a signal handler easier.
于 2018-06-28T17:58:32.517 回答
0

无法保证 10ms 的循环时间。所有睡眠功能都至少睡眠所需的时间。对于便携式解决方案,请使用std::this_thread::sleep_for

#include <iostream>
#include <chrono>
#include <thread>

int main()
{
    for (;;) {
        auto start = std::chrono::high_resolution_clock::now();
        std::this_thread::sleep_for(std::chrono::milliseconds{10});
        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double, std::milli> elapsed = end-start;
        std::cout << "Waited " << elapsed.count() << " ms\n";
    }
}

根据您要执行的操作,请查看Howard Hinnants日期库。

于 2018-06-28T18:28:16.090 回答