如何睡几微秒 [英] How to sleep for a few microseconds

查看:166
本文介绍了如何睡几微秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下code:

#include <stdio.h>
#include <time.h>
#include <math.h>

// Compile with gcc -lrt -lm -o test_clock test_clock.c

#define CLOCK CLOCK_MONOTONIC

int main(int argc, char** argv) {
    double temp, elapsed;
    int j;
    struct timespec requestStart, requestEnd, req;

    // Pseudo-sleep
    clock_gettime(CLOCK, &requestStart);
    temp = 0;
    for(j=0; j < 40; j++)
        temp += sin(j);
    clock_gettime(CLOCK, &requestEnd);
    elapsed = ( requestEnd.tv_sec - requestStart.tv_sec ) / 1e-6
                 + ( requestEnd.tv_nsec - requestStart.tv_nsec ) / 1e3;
    printf("Elapsed: %lf us\n", elapsed);

    // Nanosleep
    clock_gettime(CLOCK, &requestStart);
    req.tv_nsec = 5000;
    req.tv_sec = 0;
    clock_nanosleep(CLOCK, 0, &req, NULL);
    clock_gettime(CLOCK, &requestEnd);
    elapsed = ( requestEnd.tv_sec - requestStart.tv_sec ) / 1e-6
                 + ( requestEnd.tv_nsec - requestStart.tv_nsec ) / 1e3;

    printf("Elapsed: %lf us\n", elapsed);

}

在我的2.6.32系统,结果是

On my 2.6.32 system, the result is

Elapsed: 5.308000 us
Elapsed: 69.142000 us

我同意,这是最有可能的,因为了nanosleep()要求内核重新安排的过程。我怎样才能避免这种情况?我想保持CPU的所有权,只是身边闲置的时间precise量。

I agree that this is most likely because nanosleep() asks the kernel to reschedule the process. How can I avoid this? I want to keep ownership of the CPU and just idle around for a precise amount of time.

推荐答案

如果您希望您的应用程序能够睡眠为precisely成为可能,首先把你的应用程序实时条件

If you want your application to be able to "sleep" as precisely as possible, first put your application in realtime conditions


  • 使用实时调度类程序/线程:SCHED_FIFO SCHED_RR或

  • 提升你的程序/线程的优先级

  • 如果你要休眠低于最低限额的内核要处理,手工busywait

看一看 http://www.drdobbs.com/184402031

和其他这样的问题:了nanosleep高的cpu使用率

这篇关于如何睡几微秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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