Skip to content
Myr

timing.c

This file

Path

timing.c

139 lines · 2.4 KiB · C

Last changed by

timing: finish: use time_stamp() when stop == NULLDaniel Eklöfbefore adoption945f85d

History of this file

Take it

1#include "timing.h"23#include <stdarg.h>4#include <stdio.h>5#include <stdlib.h>67#define LOG_MODULE "timing"8#define LOG_ENABLE_DBG 09#include "log.h"10#include "xsnprintf.h"1112static struct timespec boot_up = {0};13static bool enabled = false;1415void16time_init(void)17{18    clock_gettime(CLOCK_MONOTONIC, &boot_up);19}2021void22time_enable(void)23{24    enabled = true;25}2627static void28timespec_sub(const struct timespec *a, const struct timespec *b,29             struct timespec *res)30{31    const long one_sec_in_ns = 1000000000;3233    res->tv_sec = a->tv_sec - b->tv_sec;34    res->tv_nsec = a->tv_nsec - b->tv_nsec;3536    /* tv_nsec may be negative */37    if (res->tv_nsec < 0) {38        res->tv_sec--;39        res->tv_nsec += one_sec_in_ns;40    }41}4243void44time_since_boot(const char *fmt, ...)45{46    if (!enabled)47        return;4849    struct timespec stop;50    clock_gettime(CLOCK_MONOTONIC, &stop);5152    struct timespec diff;53    timespec_sub(&stop, &boot_up, &diff);5455    va_list va1, va2;56    va_start(va1, fmt);57    va_copy(va2, va1);5859    int len = vsnprintf(NULL, 0, fmt, va1);60    va_end(va1);6162    char msg[len + 1];63    xvsnprintf(msg, len + 1, fmt, va2);64    va_end(va2);656667    LOG_WARN("%s: %llds %lldµs since boot-up", msg,68             (unsigned long long)diff.tv_sec,69             (unsigned long long)diff.tv_nsec / 1000);70}7172static struct timespec *73time_stamp(void)74{75    if (!enabled)76        return NULL;7778    struct timespec *ret = malloc(sizeof(*ret));79    if (ret == NULL)80        return NULL;8182    clock_gettime(CLOCK_MONOTONIC, ret);83    return ret;84}8586struct timespec *87time_begin(void)88{89    return time_stamp();90}9192struct timespec *93time_end(void)94{95    return time_stamp();96}9798void99time_finish(struct timespec *start, struct timespec *stop, const char *fmt, ...)100{101    if (!enabled) {102        free(start);103        free(stop);104        return;105    }106107    if (start == NULL)108        return;109110    if (stop == NULL) {111        stop = time_stamp();112113        if (stop == NULL) {114            free(start);115            return;116        }117    }118119    struct timespec diff;120    timespec_sub(stop, start, &diff);121122    va_list va1, va2;123    va_start(va1, fmt);124    va_copy(va2, va1);125126    int len = vsnprintf(NULL, 0, fmt, va1);127    va_end(va1);128129    char msg[len + 1];130    xvsnprintf(msg, len + 1, fmt, va2);131    va_end(va2);132133    LOG_WARN("%s in %llds %lldµs", msg,134             (unsigned long long)diff.tv_sec,135             (unsigned long long)diff.tv_nsec / 1000);136137    free(start);138    free(stop);139}