c++ - 如何在 C++ 中获得以毫秒为单位的系统启动时间?

标签 c++ time ctime

如何获得自系统启动以来的系统运行时间?我找到的只是自纪元以来的时间,没有别的。

例如,ctime 库中的 time() 之类的东西,但它只给我一个自纪元以来的秒数。我想要类似 time() 的东西,但自系统启动以来。

最佳答案

它依赖于操作系统,并且已经在 stackoverflow 上回答了多个系统。

#include<chrono> // for all examples :)

Windows ...

使用GetTickCount64() (分辨率通常为 10-16 毫秒)

#include <windows>
// ...
auto uptime = std::chrono::milliseconds(GetTickCount64());

Linux ...

...使用/proc/uptime

#include <fstream>
// ...
std::chrono::milliseconds uptime(0u);
double uptime_seconds;
if (std::ifstream("/proc/uptime", std::ios::in) >> uptime_seconds)
{
  uptime = std::chrono::milliseconds(
    static_cast<unsigned long long>(uptime_seconds*1000.0)
  );
}

... 使用 sysinfo (分辨率1秒)

#include <sys/sysinfo.h>
// ...
std::chrono::milliseconds uptime(0u);
struct sysinfo x;
if (sysinfo(&x) == 0)
{
  uptime = std::chrono::milliseconds(
    static_cast<unsigned long long>(x.uptime)*1000ULL
  );
}

OS X ...

... 使用 sysctl

#include <time.h>
#include <errno.h>
#include <sys/sysctl.h>
// ...
std::chrono::milliseconds uptime(0u);
struct timeval ts;
std::size_t len = sizeof(ts);
int mib[2] = { CTL_KERN, KERN_BOOTTIME };
if (sysctl(mib, 2, &ts, &len, NULL, 0) == 0)
{
  uptime = std::chrono::milliseconds(
    static_cast<unsigned long long>(ts.tv_sec)*1000ULL + 
    static_cast<unsigned long long>(ts.tv_usec)/1000ULL
  );
}

类 BSD 系统(或分别支持 CLOCK_UPTIMECLOCK_UPTIME_PRECISE 的系统)...

... 使用 clock_gettime (分辨率见clock_getres)

#include <time.h>
// ... 
std::chrono::milliseconds uptime(0u);
struct timespec ts;
if (clock_gettime(CLOCK_UPTIME_PRECISE, &ts) == 0)
{
  uptime = std::chrono::milliseconds(
    static_cast<unsigned long long>(ts.tv_sec)*1000ULL + 
    static_cast<unsigned long long>(ts.tv_nsec)/1000000ULL
   );
}

关于c++ - 如何在 C++ 中获得以毫秒为单位的系统启动时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30095439/

相关文章:

c++11 参数包错误行为与 Apple LLVM 7.0.0 但适用于 GCC-5.1

time - 我如何使用java找出mp3文件的持续时间/总播放时间?

c - 我如何在 C 中打印日期?

iphone - 使用 NSDateFormatter 从字符串中获取日期,无论 12 小时到 24 小时设置如何

java - 最小窗口子串我的解决方案的时间复杂度

c++ - ctime 有问题,计算函数运行时间

c++ - 循环 rand(),在下一个 rand() 上不要使用前一个?

c++ - '转换': is not a member of 'std'

c++ - 了解 GL_SHADER_STORAGE_BLOCK 绑定(bind)

c++ - 自定义内存管理器