日期:2014-05-16  浏览次数:20801 次

usleep 休眠非man描述的微妙而是毫秒级别的!
centos 5.4 系统。gcc 4.1.2
nanosleep 和 usleep 休眠级别都是毫秒,而不是man描述的纳秒和微妙。。。为什么会这样?

------解决方案--------------------
这个linux是支持的,只是有点点不准确而已。毕竟纳秒单位很小嘛。
------解决方案--------------------
你可以写个程序测试, 用nanosleep 去睡 1000*1000*100,肯定是睡100ms左右。
------解决方案--------------------
nanosleep和usleep的精度都是有限的,一般都在毫秒级别。
关于usleep是这么说的:

The usleep() function will cause the calling thread to be suspended from execution until either the number of real-time microseconds specified by the argument useconds has elapsed or a signal is delivered to the calling thread and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested due to the scheduling of other activity by the system.

Implementations may place limitations on the granularity of timer values. For each interval timer, if the requested timer value requires a finer granularity than the implementation supports, the actual timer value will be rounded up to the next supported value. 

程序的输出最直观了

/*-
 * Copyright (C) mymtom
 *
 * vi:set ts=4 sw=4:
 */
#ifndef lint
static const char rcsid[] = "$Id$";
#endif /* not lint */

/**
 * @file        usleep.c
 * @brief       
 */

#include <unistd.h>

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

static char *getlongtime(char *buf)
{
        struct tm tms;
        struct timeval tvs;

        gettimeofday(&tvs, NULL);
        tms = *localtime(&tvs.tv_sec);
        strftime(buf, 19 + 1, "%Y-%m-%d %H:%M:%S", &tms);
        sprintf(buf + 19, ".%06d", tvs.tv_usec);
        return buf;
}

int main(int argc, char *argv[])
{
        char buf[26 + 1];

        printf("%s\n", getlongtime(buf));

        usleep(5);
    &nbs