It depends on the OS and already answered for several systems in the thread stack.
#include<chrono> // for all examples :)
using GetTickCount64() (resolution usually 10-16 milliseconds)
#include <windows> // ... auto uptime = std::chrono::milliseconds(GetTickCount64());
... 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) ); }
... using sysinfo (resolution 1 second)
#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 ); }
#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-like systems (or systems supporting CLOCK_UPTIME or CLOCK_UPTIME_PRECISE respectively) ...
#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 ); }
source share