summaryrefslogtreecommitdiff
path: root/src/mytime.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/mytime.c')
-rw-r--r--src/mytime.c57
1 files changed, 57 insertions, 0 deletions
diff --git a/src/mytime.c b/src/mytime.c
index ffb7323..e71259b 100644
--- a/src/mytime.c
+++ b/src/mytime.c
@@ -1,6 +1,8 @@
#include "mytime.h"
#include <assert.h>
+#include <math.h>
+#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
@@ -36,3 +38,58 @@ void progress_time(uint64_t diff) {
// Right now the diff is only seconds resolution
global_time.tv_sec += diff;
}
+
+struct timespec time_from_double(double t) {
+ double fraction;
+ double integral;
+ fraction = modf(t, &integral);
+ return (struct timespec) {
+ .tv_sec = integral,
+ .tv_nsec = fraction * 1000000000.0,
+ };
+}
+
+struct formatted_time format_time(struct timespec time) {
+ struct formatted_time res = {0};
+
+ struct tm tm;
+ gmtime_r(&time.tv_sec, &tm);
+ if(strftime(res.buf, 32, "%Y-%m-%d %H:%M:%S", &tm) >= 32) {
+ abort();
+ }
+
+ return res;
+}
+
+struct formatted_time format_duration(struct timespec time) {
+ struct formatted_time res = {0};
+
+ int hours = time.tv_sec / 3600;
+ int mins = (time.tv_sec % 3600) / 60;
+ int secs = time.tv_sec % 60;
+
+ if (hours > 0) {
+ snprintf(res.buf, 32, "%dh %02dm %02ds", hours, mins, secs);
+ } else if (mins > 0) {
+ snprintf(res.buf, 32, "%dm %02ds", mins, secs);
+ } else {
+ snprintf(res.buf, 32, "%ds", secs);
+ }
+
+
+ return res;
+}
+
+struct timespec time_sub(const struct timespec *t1, const struct timespec *t2) {
+ assert(t1);
+ assert(t2);
+ struct timespec diff = {
+ .tv_sec = t1->tv_sec - t2->tv_sec,
+ .tv_nsec = t1->tv_nsec - t2->tv_nsec
+ };
+ if (diff.tv_nsec < 0) {
+ diff.tv_nsec += 1000000000;
+ diff.tv_sec--;
+ }
+ return diff;
+}