aboutsummaryrefslogtreecommitdiff
path: root/src/timing.h
blob: b48028eed399dfb012ce05fd5f8e8605e1b2e52b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#ifndef MACOS_TIMING_H
#define MACOS_TIMING_H

#include <stdint.h>
#include <CoreServices/CoreServices.h>
#include <mach/mach_time.h>

#define BEGIN_SCOPED_TIMED_BLOCK(note) \
    do { \
        struct timing_info timing; \
        if (profile) begin_timing(&timing, note)
#define END_SCOPED_TIMED_BLOCK() \
        if (profile) end_timing(&timing); \
    } while (0)

#define BEGIN_TIMED_BLOCK(note) \
    struct timing_info timing; \
    if (profile) begin_timing(&timing, note)
#define END_TIMED_BLOCK() \
    if (profile) end_timing(&timing)

#define internal static
#define global   static

global bool profile;

struct timing_info
{
    char *note;
    uint64_t start;
    uint64_t end;
    double ms;
};

void begin_timing(struct timing_info *timing, char *note);
void end_timing(struct timing_info *timing);

internal inline uint64_t
macos_get_wall_clock(void)
{
    return mach_absolute_time();
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
static inline uint64_t macos_get_nanoseconds_elapsed(uint64_t start, uint64_t end)
{
    uint64_t elapsed = end - start;
    Nanoseconds nano = AbsoluteToNanoseconds(*(AbsoluteTime *) &elapsed);
    return *(uint64_t *) &nano;
}
#pragma clang diagnostic pop

internal inline double
macos_get_milliseconds_elapsed(uint64_t start, uint64_t end)
{
    uint64_t ns = macos_get_nanoseconds_elapsed(start, end);
    return (double)(ns / 1000000.0);
}

internal inline double
macos_get_seconds_elapsed(uint64_t start, uint64_t end)
{
    uint64_t ns = macos_get_nanoseconds_elapsed(start, end);
    return (double)(ns / 1000000000.0);
}

void begin_timing(struct timing_info *timing, char *note) {
    timing->note = note;
    timing->start = macos_get_wall_clock();
}

void end_timing(struct timing_info *timing) {
    timing->end = macos_get_wall_clock();
    timing->ms  = macos_get_milliseconds_elapsed(timing->start, timing->end);
    if (timing->note) {
        printf("%6.4fms (%s)\n", timing->ms, timing->note);
    } else {
        printf("%6.4fms\n", timing->ms);
    }
}

#undef internal
#undef global

#endif