如何在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.
答
使用
...使用
... using
...使用
...使用
类BSD系统(或分别支持
...使用
BSD-like systems (or systems supporting
... using
它取决于操作系统,并且已经在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
);
}