Skip to content

Commit

Permalink
high resolution system time
Browse files Browse the repository at this point in the history
  • Loading branch information
Linem Davton committed May 3, 2024
0 parents commit e61a128
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
build/
31 changes: 31 additions & 0 deletions clock_res.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/bin/bash

# Define a temporary source file
SOURCE_FILE=$(mktemp /tmp/clock_getres.XXXXXX.c)

# Create a C program to get clock resolutions
cat <<EOF >$SOURCE_FILE
#include <stdio.h>
#include <time.h>
void print_clock_res(clockid_t clk_id, const char* name) {
struct timespec res;
clock_getres(clk_id, &res);
printf("%s resolution: %ld seconds, %ld nanoseconds\\n", name, res.tv_sec, res.tv_nsec);
}
int main() {
print_clock_res(CLOCK_REALTIME, "CLOCK_REALTIME");
print_clock_res(CLOCK_MONOTONIC, "CLOCK_MONOTONIC");
return 0;
}
EOF

# Compile the C program
gcc -o /tmp/clock_getres $SOURCE_FILE

# Run the compiled program
/tmp/clock_getres

# Clean up
rm $SOURCE_FILE /tmp/clock_getres
44 changes: 44 additions & 0 deletions high_res_time.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#include <stdio.h>
#include <time.h>

void print_clock_res(clockid_t clk_id, const char *name) {
struct timespec res;
clock_getres(clk_id, &res);
printf("%s resolution: %ld seconds, %ld nanoseconds\n", name, res.tv_sec,
res.tv_nsec);
}

void print_formatted_time(struct timespec *ts) {
char buffer[100];
struct tm *tm_info;

tm_info = localtime(&ts->tv_sec); // Convert time_t seconds to struct tm
strftime(buffer, sizeof(buffer), "%a %H:%M:%S",
tm_info); // Format date and time

long milliseconds =
ts->tv_nsec / 1000000; // Convert nanoseconds to milliseconds
long microseconds = (ts->tv_nsec % 1000000) / 1000; // Remaining microseconds
long nanoseconds = ts->tv_nsec % 1000; // Remaining nanoseconds

printf("%s.%03ld,%03ld,%03ld\n", buffer, milliseconds, microseconds,
nanoseconds);
}

int main() {
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) == 0) {
printf("CLOCK_REALTIME: ");
print_formatted_time(&ts);
} else {
perror("Failed to get CLOCK_REALTIME");
}

if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
printf("CLOCK_MONOTONIC: %ld seconds, %ld nanoseconds\n", ts.tv_sec,
ts.tv_nsec);
} else {
perror("Failed to get CLOCK_MONOTONIC");
}
return 0;
}

0 comments on commit e61a128

Please sign in to comment.