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

use*_*112 8 c++ time ctime

如何从系统启动以来获得系统启动时间?我发现的只是时代以来的时间而已.

例如,像ctime库中的time(),但它只给我一个自纪元以来秒的值.我想要像time()这样的东西但是从系统的开始.

Pix*_*ist 27

它依赖于操作系统,已经在stackoverflow上为多个系统提供了答案.

#include<chrono> // for all examples :)
Run Code Online (Sandbox Code Playgroud)

Windows ...

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

#include <windows>
// ...
auto uptime = std::chrono::milliseconds(GetTickCount64());
Run Code Online (Sandbox Code Playgroud)

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)
  );
}
Run Code Online (Sandbox Code Playgroud)

...使用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
  );
}
Run Code Online (Sandbox Code Playgroud)

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
  );
}
Run Code Online (Sandbox Code Playgroud)

类似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
   );
}
Run Code Online (Sandbox Code Playgroud)

  • 此外,是否有跨平台的方式获得它? (2认同)