gpt4 book ai didi

C++ 在 Linux 上获取毫秒时间——clock() 似乎不能正常工作

转载 作者:IT老高 更新时间:2023-10-28 11:55:51 33 4
gpt4 key购买 nike

在 Windows 上,clock() 以毫秒为单位返回时间,但在我正在研究的这个 Linux 机器上,它将它四舍五入到最接近的 1000,因此精度仅为“秒”级别而不是毫秒级别。

我使用 QTime 类找到了 Qt 的解决方案,实例化一个对象并在其上调用 start() 然后调用 elapsed()获取经过的毫秒数。

我很幸运,因为我一开始就使用 Qt,但我想要一个不依赖第三方库的解决方案,

没有标准的方法吗?

更新

请不要推荐 Boost ..

如果 Boost 和 Qt 可以做到,那肯定不是魔法,它们一定有某种标准在使用!

最佳答案

#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
struct timeval start, end;

long mtime, seconds, useconds;

gettimeofday(&start, NULL);
usleep(2000);
gettimeofday(&end, NULL);

seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;

mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

printf("Elapsed time: %ld milliseconds\n", mtime);

return 0;
}

关于C++ 在 Linux 上获取毫秒时间——clock() 似乎不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/588307/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com