Root/usrp/peak.c

1#include <stdlib.h>
2#include <stdio.h>
3#include <unistd.h>
4#include <math.h>
5#include <sys/types.h>
6
7
8#define PERC_DEFAULT 0.9
9
10
11static int comp(const void *_a, const void *_b)
12{
13    float a = *(const float *) _a;
14    float b = *(const float *) _b;
15
16    return a < b ? -1 : a > b;
17}
18
19
20static void find_peak(int skip, float percentile, int dump)
21{
22    float max = 0;
23    float c[2], a;
24    float *rec = NULL;
25    int e = 0, n = 0;
26
27    while (1) {
28        size_t s;
29
30        s = fread(c, sizeof(c), 1, stdin);
31        if (!s) {
32            if (!ferror(stdin))
33                break;
34            if (s < 0) {
35                perror("read");
36                exit(1);
37            }
38        }
39        if (skip) {
40            skip--;
41            continue;
42        }
43        a = hypotf(c[0], c[1]);
44        if (a > max)
45            max = a;
46        if (e <= n) {
47            e = e ? e*2 : 10000;
48            rec = realloc(rec, e*sizeof(float));
49            if (!rec) {
50                perror("realloc");
51                exit(1);
52            }
53        }
54        rec[n] = a;
55        n++;
56    }
57
58    if (skip >= n) {
59        fprintf(stderr, "cannot skip %d of %d entries\n", skip, n);
60        exit(1);
61    }
62    rec += skip;
63    n -= skip;
64
65    qsort(rec, n, sizeof(float), comp);
66
67    if (!dump)
68        printf("%f %f\n", max, rec[(int) (percentile*n)]);
69    else {
70        int i;
71
72        for (i = 0; i < n; i += 1000)
73            printf("%f %f\n", (double) i/n, rec[i]);
74    }
75}
76
77
78static void usage(const char *name)
79{
80    fprintf(stderr,
81"usage: %s [-s skip] [percentile]\n"
82" %s [-s skip] -d\n\n"
83" percentile select the specified percentile (default: %g)\n\n"
84" -d dump the histogram\n"
85" -s skip skip this number of samples from the beginning (default: 0)\n"
86    , name, name, PERC_DEFAULT);
87    exit(1);
88}
89
90
91int main(int argc, char **argv)
92{
93    int dump = 0, skip = 0;
94    float perc = PERC_DEFAULT;
95    int c;
96
97    while ((c = getopt(argc, argv, "ds:")) != EOF)
98        switch (c) {
99        case 'd':
100            dump = 1;
101            break;
102        case 's':
103            skip = atoi(optarg);
104            break;
105        default:
106            usage(*argv);
107        }
108
109    switch (argc-optind) {
110    case 0:
111        break;
112    case 1:
113        if (dump)
114            usage(*argv);
115        perc = atof(argv[optind]);
116        break;
117    default:
118        usage(*argv);
119    }
120
121    find_peak(skip, perc, dump);
122
123    return 0;
124}
125

Archive Download this file



interactive