Skip to content

Instantly share code, notes, and snippets.

@nyg
Last active April 1, 2024 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyg/dbdef21a1a0632c389d4d756d4fc1c0d to your computer and use it in GitHub Desktop.
Save nyg/dbdef21a1a0632c389d4d756d4fc1c0d to your computer and use it in GitHub Desktop.
Get boot time and uptime on macOS in C.
// Tested on macOS 10.12.
//
// Usage:
// $ clang uptime.c && ./a.out
// boot time (UNIX time): 1502299682.147510
// uptime (seconds): 410563.269028116
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <sys/sysctl.h>
struct timeval get_boottime();
struct timespec get_uptime();
void print_error();
int main(int argc, char** argv)
{
struct timeval boottime = get_boottime();
printf("boot time (UNIX time): %li.%06i\n", boottime.tv_sec, boottime.tv_usec);
struct timespec uptime = get_uptime();
printf("uptime (seconds): %li.%09li\n", uptime.tv_sec, uptime.tv_nsec);
}
struct timeval get_boottime()
{
struct timeval boottime;
int mib[2] = { CTL_KERN, KERN_BOOTTIME };
size_t size = sizeof(boottime);
if (0 != sysctl(mib, 2, &boottime, &size, NULL, 0))
{
print_error();
}
return boottime;
}
struct timespec get_uptime()
{
struct timespec uptime;
if (0 != clock_gettime(CLOCK_MONOTONIC_RAW, &uptime))
{
print_error();
}
return uptime;
}
void print_error()
{
printf("%s\n", strerror(errno));
exit(errno);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment