如何在C ++中以毫秒为单位获取系统正常运行时间? [英] How do I get system up time in milliseconds in c++?

查看:110
本文介绍了如何在C ++中以毫秒为单位获取系统正常运行时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自系统启动以来,如何获得系统正常运行时间?我发现的只是时代以来的时间.

How do I get system up time since the start of the system? All I found was time since epoch and nothing else.

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

For example, something like time() in ctime library, but it only gives me a value of seconds since epoch. I want something like time() but since the start of the system.

推荐答案

它取决于操作系统,并且已经在stackoverflow上针对多个系统进行了回答.

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

Windows ...

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

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

Linux ...

...使用/proc/uptime

Linux ...

... using /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_UPTIME CLOCK_UPTIME_PRECISE 的系统)...

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

BSD-like systems (or systems supporting CLOCK_UPTIME or CLOCK_UPTIME_PRECISE respectively) ...

... using clock_gettime (resolution see 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 ++中以毫秒为单位获取系统正常运行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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