0

我只被允许使用这个功能,我试图找出一种方法来计算经过的时间,有什么想法吗?我很困惑..

# include <sys/types.h>
# include <sys/time.h>
# include <stdio.h>
# include <unistd.h>


int main(int argc, char* argv[])
{
    struct timeval now;
    struct timeval start;
    int t_now;
    int t_stop;
    int t_start;
    int i;

    gettimeofday(&start, NULL);
    t_start = start.tv_usec / 1000;
    t_stop = t_start + 200;

    while (42)
    {
        usleep(2000);
        gettimeofday(&now, NULL);
        t_now = now.tv_usec / 1000;
        if (t_now - t_stop > -1)
        {
            break;
        }
        printf ("%d\n", t_now);
        usleep(2000);
    }
    return 0;
}

我正在这样做,但它会继续循环,并且不会停止..

4

1 回答 1

0

这个

t_start = start.tv_usec / 1000;

没有做你所期望的。tv_usec 只有几分之一秒,你需要

long long msec = (start.tv_sec * 1000) + start.tv_usec/1000;

获得总毫秒

于 2022-03-01T00:17:44.550 回答