how to calculate milliseconds using timeval structure?

旧城冷巷雨未停 提交于 2019-12-10 21:11:15

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/18650057/how-to-calculate-milliseconds-using-timeval-structure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!