Programmatically Getting System Boot Up Time in C++ (Windows)

Programmatically getting system boot up time in c++ (windows)

GetTickCount64 "retrieves the number of milliseconds that have elapsed since the system was started."

Once you know how long the system has been running, it is simply a matter of subtracting this duration from the current time to determine when it was booted. For example, using the C++11 chrono library (supported by Visual C++ 2012):

auto uptime = std::chrono::milliseconds(GetTickCount64());
auto boot_time = std::chrono::system_clock::now() - uptime;

How do I get system up time in milliseconds in c++?

It is OS dependant and already answered for several systems on stackoverflow.

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

Windows ...

using GetTickCount64() (resolution usually 10-16 millisecond)

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

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)
);
}

... 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
);
}

OS X ...

... using 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-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
);
}

How to get Windows boot time?

I've checked at how Task Manager does it, and turns out it uses the ZwQuerySystemInformation(SystemTimeOfDayInformation, ...) function, which receives the SYSTEM_TIMEOFDAY_INFORMATION structure.

typedef struct _SYSTEM_TIMEOFDAY_INFORMATION {
LARGE_INTEGER BootTime;
LARGE_INTEGER CurrentTime;
LARGE_INTEGER TimeZoneBias;
ULONG TimeZoneId;
ULONG Reserved;
ULONGLONG BootTimeBias;
ULONGLONG SleepTimeBias;
} SYSTEM_TIMEOFDAY_INFORMATION, *PSYSTEM_TIMEOFDAY_INFORMATION;

(source)

BootTime is what you're looking for.

For something more documented, I think GetTickCount64 will do.

Programmatically compute the start time of a process on Windows

If I understand you right you want to know what time your process started, correct? So you'll want to look into GetProcessTimes

If the process you're interested in is the current process, you can use GetCurrentProcess() to get the process handle that you'll need to call GetProcessTimes() this returns a pseudo-handle that you don't need to close.

How to get the system uptime in Windows?

Following are eight ways to find the Uptime in Windows OS.

1: By using the Task Manager

In Windows Vista and Windows Server 2008, the Task Manager has been beefed up to show additional information about the system. One of these pieces of info is the server’s running time.

  1. Right-click on the Taskbar, and click Task Manager. You can also click CTRL+SHIFT+ESC to get to the Task Manager.
  2. In Task Manager, select the Performance tab.
  3. The current system uptime is shown under System or Performance ⇒ CPU for Win 8/10.

    "Up Time" field in Task Manager

2: By using the System Information Utility

The systeminfo command line utility checks and displays various system statistics such as installation date, installed hotfixes and more.
Open a Command Prompt and type the following command:

systeminfo

You can also narrow down the results to just the line you need:

systeminfo | find "System Boot Time:"

Sample Image

3: By using the Uptime Utility

Microsoft have published a tool called Uptime.exe. It is a simple command line tool that analyses the computer's reliability and availability information. It can work locally or remotely. In its simple form, the tool will display the current system uptime. An advanced option allows you to access more detailed information such as shutdown, reboots, operating system crashes, and Service Pack installation.

Read the following KB for more info and for the download links:

  • MSKB232243: Uptime.exe Tool Allows You to Estimate Server Availability with Windows NT 4.0 SP4 or Higher.

To use it, follow these steps:

  1. Download uptime.exe from the above link, and save it to a folder,
    preferably in one that's in the system's path (such as SYSTEM32).
  2. Open an elevated Command Prompt window. To open an elevated Command
    Prompt, click Start, click All Programs, click Accessories,
    right-click Command Prompt, and then click Run as administrator. You
    can also type CMD in the search box of the Start menu, and when you
    see the Command Prompt icon click on it to select it, hold
    CTRL+SHIFT and press ENTER.
  3. Navigate to where you've placed the uptime.exe utility.
  4. Run the uptime.exe utility. You can add a /? to the command in order
    to get more options.
    Sample Image

It does not offer many command line parameters:

C:\uptimefromcodeplex\> uptime /?
usage: Uptime [-V]
-V display version

C:\uptimefromcodeplex\> uptime -V
version 1.1.0

3.1: By using the old Uptime Utility

There is an older version of the "uptime.exe" utility. This has the advantage of NOT needing .NET. (It also has a lot more features beyond simple uptime.)

Download link: Windows NT 4.0 Server Uptime Tool (uptime.exe) (final x86)

C:\uptimev100download>uptime.exe /?

UPTIME, Version 1.00
(C) Copyright 1999, Microsoft Corporation

Uptime [server] [/s ] [/a] [/d:mm/dd/yyyy | /p:n] [/heartbeat] [/? | /help]
server Name or IP address of remote server to process.
/s Display key system events and statistics.
/a Display application failure events (assumes /s).
/d: Only calculate for events after mm/dd/yyyy.
/p: Only calculate for events in the previous n days.
/heartbeat Turn on/off the system's heartbeat
/? Basic usage.
/help Additional usage information.

4: By using the NET STATISTICS Utility

Another easy method, if you can remember it, is to use the approximate information found in the statistics displayed by the NET STATISTICS command.
Open a Command Prompt and type the following command:

net statistics workstation

The statistics should tell you how long it’s been running, although in some cases this information is not as accurate as other methods.

Sample Image

5: By Using the Event Viewer

Probably the most accurate of them all, but it does require some clicking. It does not display an exact day or hour count since the last reboot, but it will display important information regarding why the computer was rebooted and when it did so. We need to look at Event ID 6005, which is an event that tells us that the computer has just finished booting, but you should be aware of the fact that there are virtually hundreds if not thousands of other event types that you could potentially learn from.

Note: BTW, the 6006 Event ID is what tells us when the server has gone down, so if there’s much time difference between the 6006 and 6005 events, the server was down for a long time.

Note: You can also open the Event Viewer by typing eventvwr.msc in the Run command, and you might as well use the shortcut found in the Administrative tools folder.


  1. Click on Event Viewer (Local) in the left navigation pane.
  2. In the middle pane, click on the Information event type, and scroll down till you see Event ID 6005. Double-click the 6005 Event ID, or right-click it and select View All Instances of This Event.
  3. A list of all instances of the 6005 Event ID will be displayed. You can examine this list, look at the dates and times of each reboot event, and so on.
  4. Open Server Manager tool by right-clicking the Computer icon on the start menu (or on the Desktop if you have it enabled) and select Manage. Navigate to the Event Viewer.

Sample Image

5.1: Eventlog via PowerShell

Get-WinEvent -ProviderName eventlog | Where-Object {$_.Id -eq 6005 -or $_.Id -eq 6006}

6: Programmatically, by using GetTickCount64

GetTickCount64 retrieves the number of milliseconds that have elapsed since the system was started.

7: By using WMI

wmic os get lastbootuptime

8: The new uptime.exe for Windows XP and up

Like the tool from Microsoft, but compatible with all operating systems up to and including Windows 10 and Windows Server 2016, this uptime utility does not require an elevated command prompt and offers an option to show the uptime in both DD:HH:MM:SS and in human-readable formats (when executed with the -h command-line parameter).

Additionally, this version of uptime.exe will run and show the system uptime even when launched normally from within an explorer.exe session (i.e. not via the command line) and pause for the uptime to be read:

Sample Image

and when executed as uptime -h:

Sample Image

What API do I call to get the system uptime?

The system call you're looking for is sysinfo().

It's defined in sys/sysinfo.h

Its signature is:
int sysinfo(struct sysinfo *info)

Since kernel 2.4, the structure has looked like this:

struct sysinfo {
long uptime; /* Seconds since boot */
unsigned long loads[3]; /* 1, 5, and 15 minute load averages */
unsigned long totalram; /* Total usable main memory size */
unsigned long freeram; /* Available memory size */
unsigned long sharedram; /* Amount of shared memory */
unsigned long bufferram; /* Memory used by buffers */
unsigned long totalswap; /* Total swap space size */
unsigned long freeswap; /* swap space still available */
unsigned short procs; /* Number of current processes */
unsigned long totalhigh; /* Total high memory size */
unsigned long freehigh; /* Available high memory size */
unsigned int mem_unit; /* Memory unit size in bytes */
char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */
};

Have fun!

Retrieve system uptime using C#

public TimeSpan UpTime {
get {
using (var uptime = new PerformanceCounter("System", "System Up Time")) {
uptime.NextValue(); //Call this an extra time before reading its value
return TimeSpan.FromSeconds(uptime.NextValue());
}
}
}

How to Automatically Turn on a Computer at a Specified Time

As some people have said, and as far as I can find it is not possible to schedule a normal PC turn on for a considerable range of PCs unless you use another machine and the wake on LAN capability.
However you could use waitable timers to wake from hibernation or suspension. Two sates that can be reached programmatically via the SetSuspendState API function. Other
three Windows API functions will help you with the second approach:

  1. CreateWaitableTimer
  2. SetWaitableTimer
  3. CancelWaitableTimer

I do not recommend to hack any BIOS configuration at all. For safety just use what your system provides in the form of a well documented API. Those hacks sometimes lead to undesired or unexpected behavior.



Related Topics



Leave a reply



Submit