需要对 timespec 结构有清晰的认识 [英] Need clear idea about timespec structure

查看:44
本文介绍了需要对 timespec 结构有清晰的认识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我使用 struct timespec 如下

struct timespec start, end;clock_gettime(CLOCK_REALTIME,&start);/* 做点什么 */clock_gettime(CLOCK_REALTIME,&end);

它返回一个值 ((((unsigned64)start.tv_sec) * ((unsigned64)(1000000000L))) + ((unsigned64)(start.tv_nsec))))>

谁能告诉我们为什么我们使用 unsigned64 格式并帮助我详细理解这个结构?我在我的研究中使用此代码,以纳秒精度计算代码执行时间

解决方案

无符号 32 位类型(如现代平台上的 unsigned int)的最大值略高于 40 亿.如果您有 5 并将其乘以 10 亿(就像在问题中的代码中所做的那样),您将得到 50 亿的值,大于 32 位无符号类型中可以包含的值.输入 64 位类型,它可以容纳 lot 更高的值(18446744073709551615 更准确地说,与无符号的 32 位最大值进行比较值只有 4294967295).

<小时>

顺便说一句,代码可以简化为

start.tv_sec * 1000000000ULL + start.tv_nsec

这种简化是可能的,因为编译器会根据需要自动将较低精度的类型和值转换为较高精度.由于表达式中有一个 unsigned long long(这就是 ULL 的意思)文字值,表达式的其余部分也将转换为 unsigned long long,结果将是 unsigned long long 类型.

In my project I'm using struct timespec as follows

struct timespec start, end;
clock_gettime(CLOCK_REALTIME,&start);
/* Do something */
clock_gettime(CLOCK_REALTIME,&end);

It returns a value as ((((unsigned64)start.tv_sec) * ((unsigned64)(1000000000L))) + ((unsigned64)(start.tv_nsec))))

Can anyone tell why we are using the unsigned64 format and also help me understand this structure in detail?? I'm using this code in my study about time calculation in nanoseconds precision for the code execution time taken

解决方案

An unsigned 32-bit type (like unsigned int on modern platforms) have a max value of a little over four billion. If you have 5 and multiply that with one billion (like done in the code in the question) you will get a value of five billion, larger than can be contained in a 32-bit unsigned type. Enter 64-bit types, which can hold a lot higher values (18446744073709551615 to be more precise, to compare with an unsigned 32-bit max value of only 4294967295).


By the way, the code can be simplified like

start.tv_sec * 1000000000ULL + start.tv_nsec

This simplification is possible because the compiler will automatically convert lower-precision types and values to higher-precision as needed. As you have an unsigned long long (that's what the ULL means) literal value in the expression, the rest of the expression will also be converted to unsigned long long and the result will be of type unsigned long long.

这篇关于需要对 timespec 结构有清晰的认识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆