两次 gettimeofday() 调用的差异给出负数

Difference of two gettimeofday() calls gives negative number

我正在尝试计算系统调用的平均开销,因此我重复执行 0 字节读取系统调用并计算平均开销作为时间差除以迭代次数。但是有时当我这样做时,我会得到一个负数。这是我的代码:

#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
#define NUM_ITER 1000000
#define NUM_EPOCHS 10

int main(){
    char buf[1];
    struct timeval tv1, tv2;
    for(int i = 0; i<NUM_EPOCHS; i++){
        gettimeofday(&tv1, NULL);
        for(int j = 0; j < NUM_ITER; j++)
            read(0, buf, 0);
        gettimeofday(&tv2, NULL);
        float time_of_sys_call = (float)(tv2.tv_usec - tv1.tv_usec) / NUM_ITER;
        printf("Avg cost of system call: %fms\n", time_of_sys_call);
    }
}

这是示例输出:

Avg cost of system call: 0.199954ms
Avg cost of system call: 0.213105ms
Avg cost of system call: 0.203455ms
Avg cost of system call: 0.200443ms
Avg cost of system call: -0.793516ms
Avg cost of system call: 0.203922ms
Avg cost of system call: 0.209279ms
Avg cost of system call: 0.201137ms
Avg cost of system call: 0.204261ms
Avg cost of system call: -0.800930ms

知道这里发生了什么吗?

tv_usec 给出当前秒内的微秒数。当时间累计到整秒后,tv_sec增加,tv_usec从零重新开始

当您从重启前不久的数字中减去重启后不久的数字时,结果为负数。