如何使用timeval结构计算毫秒数? [英] how to calculate milliseconds using timeval structure?

查看:1019
本文介绍了如何使用timeval结构计算毫秒数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从类型为timeval的变量中以毫秒为单位检索值。以下是我的尝试:

I want to retrieve values in milliseconds from a variable of type timeval. Below is my attempt:

timeval* time;
long int millis = (time->tv_sec * 1000) + (time->tv_usec / 1000);
printf("Seconds : %ld, Millis : %ld", time->tv_sec, millis);

Output => Seconds : 1378441469, Millis : -243032358

问题是我在减去毫秒值。这段代码有什么问题?

Issue is I am getting millisecond values in minus. What is wrong with this snippets?

推荐答案

假设你没有正确初始化 time ,这是因为你在将 time-> tv_sec 乘以1000时溢出了。在你的情况中,它已经是14亿了,并且你正在进行的有符号乘法最终结束溢出21亿左右。使用64位乘法来解决它:

Assuming you did correctly initialize time, it's because you're overflowing when multiplying time->tv_sec by 1000. In your case, it's 1.4 billion already, and the signed multiplication you're doing ends up overflowing at 2.1 billion or so. Use 64-bit multiplication to get around it:

uint64_t millis = (time->tv_sec * (uint64_t)1000) + (time->tv_usec / 1000);

确保使用合理的格式将其打印出来。

Make sure to print it out using a reasonable format.

这篇关于如何使用timeval结构计算毫秒数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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