首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >两次gettimeofday()调用的差值为负数

两次gettimeofday()调用的差值为负数
EN

Stack Overflow用户
提问于 2020-02-23 05:46:04
回答 1查看 135关注 0票数 3

我试图计算系统调用的平均开销,所以我重复执行一个0字节的read系统调用,并计算平均开销,即时间差除以迭代次数。然而,有时当我这样做时,我会得到一个负数。下面是我的代码:

代码语言:javascript
复制
#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);
    }
}

以下是示例输出:

代码语言:javascript
复制
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

知道这是怎么回事吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-23 05:47:36

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

如果从重新启动之前不久的数字中减去重新启动后不久的数字,则结果为负。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60357137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档