使用gettimeofday的未定义行为

时间:2017-01-26 19:32:56

标签: c++ unix undefined-behavior gettimeofday

#include <iostream>
#include <sys/time.h>

static long elapsedTime(struct timeval &then)
{
    struct timeval when;
    gettimeofday(&when, NULL);
    long result = (when.tv_sec - then.tv_sec) * 1000;
    result += (when.tv_usec - then.tv_usec) / 1000;
    then = when;
    return (result > 0) ? result : 0;
}

int main()
{
    struct timeval now;
    gettimeofday(&now, NULL);

    long elapsed, everyMinute = 0;
    while (true) {
        elapsed = elapsedTime(now);
        everyMinute += elapsed;

        if (everyMinute % 1000 == 0) 
            std::cout << "After: " << everyMinute << std::endl;
    }
    return 0;
}

我试图让这个循环每分钟打印一次,但gettimeofday给了我意想不到的行为。例如,这一行std::cout << "Before: " << everyMinute << std::endl;将导致if工作但没有它我只得到零:这里是snippet但是最好插入你自己的编译器。

0 个答案:

没有答案