aboutsummaryrefslogtreecommitdiff
path: root/bench/src/Bench.c
blob: 613cdbb872380df6302bf50528707eb6ed6402e0 (plain)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <BH/Bench.h>
#include <BH/Timer.h>
#include <stdlib.h>
#include <stdio.h>


struct BH_Bench
{
    struct BH_Bench *next;
    const char *name;
    BH_BenchCallback cb;
    int started;
    size_t iterations;
};


static BH_Bench *root = NULL;
static BH_Timer *timer = NULL;


static void cleanup(void)
{
    BH_Bench *current;

    current = root;
    while (current)
    {
        BH_Bench *next = current->next;

        free(current);
        current = next;
    }
}


void BH_BenchAdd(const char *name,
                 BH_BenchCallback cb)
{
    BH_Bench *bench, *current;

    /* Allocate and fill new benchmark entry */
    bench = malloc(sizeof(*bench));
    if (!bench)
        return;

    bench->next = NULL;
    bench->name = name;
    bench->cb = cb;
    bench->started = 0;
    bench->iterations = 0;

    /* Append benchmark entry */
    current = root;
    while (current && current->next)
        current = current->next;

    if (current)
        current->next = bench;
    else
        root = bench;
}


int BH_BenchIter(BH_Bench *state)
{
    if (state->started)
    {
        int64_t millis;

        state->iterations++;
        millis = BH_TimerMilliseconds(timer);

        if (millis > 1000 && state->iterations > 10)
        {
            printf("%s\t%f ips\n", state->name, state->iterations / (millis / 1000.0f));
            return 0;
        }
    }
    else
    {
        state->started = 1;
        BH_TimerRestart(timer);
    }

    return 1;
}


int BH_BenchRun(void)
{
    BH_Bench *current;
    int result = 0;

    timer = BH_TimerNew();
    if (!timer)
    {
        printf("ERROR: Can't create timer for benchmarks");
        return -1;
    }

    printf("Running benchmarks...\n");
    current = root;
    while (current)
    {
        current->cb(current);
        current = current->next;
        fflush(stdout);
    }

    cleanup();
    return 0;
}