测量经过的时间(以 C 为单位) - 纳秒 - 浮动套管

问题描述 投票:0回答:1

我想测量两个事件之间的持续时间,例如捕获不同时间点的CPU快照。 乘以1000000000L后是否需要在这里进行强制转换?正确吗?

float get_elapsed(domain_info *dom){
    
    float temp;

    temp = (float)((dom->t2.tv_sec - dom->t1.tv_sec) * 1000000000L +(dom->t2.tv_nsec - dom->t1.tv_nsec);

    return temp;
}
c floating-point
1个回答
0
投票

我们不知道

typedef struct {} domain_info
是什么,并且表达式有不匹配的括号,因此无法编译。假设您的意思是:

#include <time.h>

typedef struct {
    struct timespec t1;
    struct timespec t2;
} domain_info;

float get_elapsed(domain_info *dom){
    return (float)((dom->t2.tv_sec - dom->t1.tv_sec) * 1000000000L +(dom->t2.tv_nsec - dom->t1.tv_nsec));
}

int main(void) {
    // ...
}

编译器会将表达式转换为

float
,因此您不需要显式转换,甚至不需要
temp
变量。

在我的系统上,tv_sec 是 64 位长,但如果是 32 位,则在

(dom->t2.tv_sec - dom->t1.tv_sec)
溢出之前只有几秒的增量。这将是未定义的行为。

float
只给您 6 到 9 个有效数字,当您按因子
1000000000L
(
1e9
) 缩放秒时,您就可以看到这一点。我建议您改用
double
,它有 15 到 17 位有效数字。

© www.soinside.com 2019 - 2024. All rights reserved.