小编Cla*_*oro的帖子

C、clock_gettime,返回了不正确的纳秒值?

我正在编写一个简单的程序,它检查经过的时间是否超过 1 秒。我使用clock_gettime()获取开始时间,然后调用sleep(5),获取新时间并检查差异是否大于1;我睡了 5 秒,那么它应该大于 5,但我的程序打印了一个奇怪的结果。

这是代码:

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

int main()
{
    struct timespec tv1,tv3,expected;
    struct timespec nano1;

    tv1.tv_nsec = 0;
    tv3.tv_nsec = 0;

    expected.tv_nsec = 400000;

    if(clock_gettime(CLOCK_MONOTONIC,&tv3) == -1){
        perror(NULL);
    }

    sleep(5);

    if(clock_gettime(CLOCK_MONOTONIC,&tv1) == -1){
        perror(NULL);
    }


    long nsec = tv1.tv_nsec - tv3.tv_nsec;

    if(nsec>expected.tv_nsec){
        printf("nsec runned: %ld   nsec timeout: %ld\n",nsec,expected.tv_nsec);
    }


    printf("elapsed nanoseconds: %ld\n",nsec);


    if((nsec>expected.tv_nsec))
        printf("expired timer\n");

    else
        printf("not expired timer\n");

    exit(EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)

我的程序的输出是:

“经过的纳秒:145130”和“未过期超时”

哪里有问题?

c posix gettime timer

2
推荐指数
1
解决办法
3734
查看次数

标签 统计

c ×1

gettime ×1

posix ×1

timer ×1