Skip to content

Instantly share code, notes, and snippets.

@ajsb85
Created April 11, 2023 11:05
Show Gist options
  • Save ajsb85/09c877dd4d19c3347eeb5672a6c4df4c to your computer and use it in GitHub Desktop.
Save ajsb85/09c877dd4d19c3347eeb5672a6c4df4c to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <assert.h>
static void set_time(void);
static void get_time(void);
int main(void)
{
set_time();
while (1) {
get_time();
sleep(0.01);
}
}
// 02:37:01.086
char* asktime(const struct tm *timeptr)
{
static char result[26];
sprintf(result, "%.2d:%.2d:%.2d\n",
timeptr->tm_hour,
timeptr->tm_min, timeptr->tm_sec);
return result;
}
static void set_time(void)
{
// Prepare the broken-down time.
// See https://en.cppreference.com/w/c/chrono/tm
struct tm initial_time = {
.tm_year = 2022 - 1900,
.tm_mon = 3 - 1,
.tm_mday = 17 - 1,
.tm_hour = 21,
.tm_min = 35,
.tm_sec = 0
};
// Convert to Unix time.
// See https://en.cppreference.com/w/c/chrono/mktime
time_t initial_unix_time = mktime(&initial_time);
// Convert to 'struct timeval'
struct timeval initial_timeval = {
.tv_sec = initial_unix_time,
.tv_usec = 0
};
// Set system time.
// See https://linux.die.net/man/2/settimeofday
int err = settimeofday(&initial_timeval, NULL);
// assert(err == 0);
printf("Time set to: %s", asctime(&initial_time));
}
static void get_time(void)
{
// Get current time as 'struct timeval'.
// See https://linux.die.net/man/2/gettimeofday
struct timeval new_timeval;
int err = gettimeofday(&new_timeval, NULL);
assert(err == 0);
// Extract Unix time
time_t new_unix_time = new_timeval.tv_sec;
int iMilliSec = new_timeval.tv_usec / 1000;
int iMicroSec = new_timeval.tv_usec;
// Convert to broken-down time
// See https://en.cppreference.com/w/c/chrono/localtime
struct tm new_time;
localtime_r(&new_unix_time, &new_time);
// 'new_time' now contains the current time components
static char result[26];
sprintf(result, "%.2d:%.2d:%.2d.%.3d\n",
new_time.tm_hour,
new_time.tm_min, new_time.tm_sec,iMilliSec);
printf("%s", result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment