Debian Codegraph @

tests/test_utils.cc

raw
1 #include <iostream>
2 #include <cstdlib>
3 #include <cerrno>
4 #include <cstring>
5 #include <cassert>
6 #include <sys/time.h>
7
8 #include "test_utils.hh"
9
10 using namespace std;
11
12 const char *parse_progname(const char *c)
13 {
14 assert(c);
15 const char * progname = strrchr(c, '/');
16 if (progname)
17 progname++;
18 else
19 progname = c;
20 return progname;
21 }
22
23 int parse_int(const char *c, int *result)
24 {
25 assert(c);
26 assert(result);
27 char *endptr;
28 errno = 0;
29 *result = strtol(c, &endptr, 0);
30 const int local_errno = errno;
31 if (local_errno || *endptr != '\0')
32 {
33 cerr << "Expected an integer, got \"" << c << "\", " << endl;
34 if (local_errno)
35 cerr << strerror(local_errno) << endl;
36 return 1;
37 }
38 return 0;
39 }
40
41 int parse_unsigned(const char *c, unsigned *result)
42 {
43 assert(c);
44 assert(result);
45 char *endptr;
46 errno = 0;
47 *result = strtoul(c, &endptr, 0);
48 const int local_errno = errno;
49 if (local_errno || *endptr != '\0')
50 {
51 cerr << "Expected an unsigned integer, got \"" << c << "\", " << endl;
52 if (local_errno)
53 cerr << strerror(local_errno) << endl;
54 return 1;
55 }
56 return 0;
57 }
58
59 int parse_double(const char *c, double *result)
60 {
61 assert(c);
62 assert(result);
63 char *endptr;
64 errno = 0;
65 *result = strtod(c, &endptr);
66 const int local_errno = errno;
67 if (local_errno || *endptr != '\0')
68 {
69 cerr << "Expected a double, got \"" << c << "\", " << endl;
70 if (local_errno)
71 cerr << strerror(local_errno) << endl;
72 return 1;
73 }
74 return 0;
75 }
76
77 int parse_vector_of_doubles(char **c, const int n, std::vector<double>* v)
78 {
79 if (n < 0)
80 {
81 cerr << "Error in parse_vector_of_doubles: negative argument count" << endl;
82 return 1;
83 }
84 for (int i=0; i<n; ++i)
85 {
86 double d;
87 if (parse_double(c[i], &d))
88 return 1;
89 v->push_back(d);
90 }
91 return 0;
92 }
93
94 double test_rng()
95 {
96 return drand48();
97 }
98
99 std::string random_string(const unsigned len)
100 {
101 std::string s(len, '\0');
102 for (unsigned i=0; i<len; ++i)
103 s[i] = static_cast<char>(test_rng()*127);
104 return s;
105 }
106
107 static unsigned long long tv_to_usec(const struct timeval* tv)
108 {
109 unsigned long long usec = tv->tv_usec;
110 usec += tv->tv_sec*1000000ULL;
111 return usec;
112 }
113
114 double time_of_run(void (*fcn)(void), const unsigned n)
115 {
116 assert(fcn);
117 assert(n);
118 struct timeval tv0, tv1;
119 gettimeofday(&tv0, NULL);
120 for (unsigned i=0; i<n; ++i)
121 fcn();
122 gettimeofday(&tv1, NULL);
123 unsigned long long udelta = tv_to_usec(&tv1) - tv_to_usec(&tv0);
124 return (double)udelta/n;
125 }