Merge branch 'master' of rtime.felk.cvut.cz:/can-benchmark
[can-benchmark.git] / latester / histogram.h
1 #ifndef HISTOGRAM_H
2 #define HISTOGRAM_H
3
4 struct histogram {
5         unsigned *data;
6         unsigned allocated;
7         unsigned resolution;
8 };
9
10 int histogram_init(struct histogram *h,
11                    unsigned max_value,
12                    unsigned resolution)
13 {
14         size_t mem;
15         h->allocated = max_value/resolution + 1;
16         h->resolution = resolution;
17         mem = h->allocated*sizeof(*h->data);
18         h->data = malloc(mem);
19         if (h->data) {
20                 memset(h->data, 0, mem);
21                 return 0;
22         } else
23                 return -1;
24 }
25
26 void histogram_add(struct histogram *h, unsigned value)
27 {
28         unsigned index = value / h->resolution;
29         if (index >= h->allocated)
30                 index = h->allocated - 1;
31         h->data[index]++;
32 }
33
34 void histogram_fprint(struct histogram *h, FILE *f)
35 {
36         unsigned long long sum = 0, cum;
37         unsigned i;
38         for (i = 0; i < h->allocated; i++)
39                 sum += h->data[i];
40         cum = sum;
41         for (i = 0; i < h->allocated; i++) {
42                 if (h->data[i] != 0) {
43                         fprintf(f, "%g %lld\n", 1e-3*(i*h->resolution), cum);
44                 }
45                 cum -= h->data[i];
46         }
47 }
48
49
50
51 #endif