我试图计算系统调用的平均开销,所以我重复执行一个0字节的read系统调用,并计算平均开销,即时间差除以迭代次数。然而,有时当我这样做时,我会得到一个负数。下面是我的代码:
#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知道这是怎么回事吗?
发布于 2020-02-23 05:47:36
tv_usec给出当前秒内的微秒数。当时间累积到一整秒时,tv_sec会增加,并且tv_usec会从零重新启动。
如果从重新启动之前不久的数字中减去重新启动后不久的数字,则结果为负。
https://stackoverflow.com/questions/60357137
复制相似问题