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

dwv*_*ldg 3 c time system-calls

我正在尝试计算系统调用的平均开销,因此我重复执行 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是示例输出:

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
Run Code Online (Sandbox Code Playgroud)

知道这里发生了什么吗?

Eri*_*hil 5

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

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