-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.cpp
121 lines (95 loc) · 2.16 KB
/
util.cpp
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
113
114
115
116
117
118
119
120
121
/* util.cpp */
#include "util.h"
#include <iostream>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;
static int verbose_flag = 0;
static int debug_flag = 0;
const int BUFSIZE(200);
static char TEMPOUT[BUFSIZE];
// Flag management
void set_verbose_on() {
verbose_flag = 1;
}
void set_debug_on() {
debug_flag = 1;
verbose_flag = 1;
}
bool is_verbose() {
return verbose_flag;
}
bool is_debug() {
return debug_flag;
}
// Display error to stderr
void error(const char * fmt, ...) {
va_list argp;
va_start(argp, fmt);
vsnprintf(TEMPOUT, sizeof(TEMPOUT), fmt, argp);
va_end(argp);
cerr << TEMPOUT << endl;
}
// Display message only when verbose
void verbose(const char * fmt, ...) {
va_list argp;
va_start(argp, fmt);
vsnprintf(TEMPOUT, sizeof(TEMPOUT), fmt, argp);
va_end(argp);
if ( verbose_flag ) {
cout << TEMPOUT << endl;
}
}
// Display message only when debugging
void debug(const char * fmt, ...) {
va_list argp;
va_start(argp, fmt);
vsnprintf(TEMPOUT, sizeof(TEMPOUT), fmt, argp);
va_end(argp);
if ( debug_flag ) {
cout << TEMPOUT << endl;
}
}
// Run a command-line utility
// Run using fork-exec combo
int run_command(char * const argv[]) {
debug("Running program %s",argv[0]);
pid_t p = fork();
if ( p == 0 ) {
if ( execvp(argv[0],argv) ) {
error("Error during execution of %s",argv[0]);
abort();
}
} else {
int status;
waitpid(p,&status,0);
debug("%s returned value %d",argv[0],status);
return status;
}
}
// Timer utilities
float diff(timespec start, timespec end) {
timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0) {
temp.tv_sec = end.tv_sec-start.tv_sec-1;
temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec-start.tv_sec;
temp.tv_nsec = end.tv_nsec-start.tv_nsec;
}
return (float)temp.tv_sec + 1e-9 * temp.tv_nsec;
}
Timer::Timer() {
reset();
}
void Timer::reset() {
clock_gettime(CLOCK_MONOTONIC_COARSE,&start_time);
}
float Timer::get_time() {
timespec temp;
clock_gettime(CLOCK_MONOTONIC_COARSE,&temp);
return diff(start_time,temp);
}