Я пытаюсь вычислить среднюю служебную нагрузку системного вызова, поэтому я неоднократно выполняю системный вызов чтения с 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
Есть идеи, что здесь происходит?