Debian Codegraph @

protolib/examples/timerTest.cpp

raw
1 #include "protoApp.h"
2 #include "protoTimer.h"
3
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <string.h>
7
8
9 // Simple self-scaling linear/non-linear histogram (one-sided)
10 class Histogram
11 {
12 public:
13 Histogram();
14 bool IsEmpty() {return (NULL == bin);}
15 void Init(unsigned long numBins, double linearity)
16 {
17 num_bins = numBins;
18 q = linearity;
19 if (bin) delete[] bin;
20 bin = NULL;
21 }
22 bool InitBins(double rangeMin, double rangeMax);
23 bool Tally(double value, unsigned long count = 1);
24 void Print(FILE* file, bool showAll = false);
25 unsigned long Count();
26 double PercentageInRange(double rangeMin, double rangeMax);
27 unsigned long CountInRange(double rangeMin, double rangeMax);
28 double Min() {return min_val;}
29 double Max() {return ((max_val < 0.0) ? 2.0*max_val : 0.5*max_val);}
30 double Percentile(double p);
31
32 private:
33
34 double GetBinValue(unsigned int i)
35 {
36 if (bin && bin[i].count)
37 {
38 return (bin[i].total / ((double)bin[i].count));
39 }
40 else
41 {
42 double x = pow(((double)i) / ((double)num_bins-1), 1.0/q);
43 x *= (max_val - min_val);
44 x += min_val;
45 return x;
46 }
47 }
48
49 typedef struct
50 {
51 double total;
52 unsigned long count;
53 } Bin;
54
55 double q;
56 unsigned long num_bins;
57 double min_val;
58 double max_val;
59 Bin* bin;
60 }; // end class Histogram
61
62
63 class TimerTestApp : public ProtoApp
64 {
65 public:
66 TimerTestApp();
67 ~TimerTestApp();
68
69 bool OnStartup(int argc, const char*const* argv);
70 bool ProcessCommands(int argc, const char*const* argv);
71 void OnShutdown();
72
73 private:
74 enum CmdType {CMD_INVALID, CMD_ARG, CMD_NOARG};
75 static const char* const CMD_LIST[];
76 static CmdType GetCmdType(const char* string);
77 bool OnCommand(const char* cmd, const char* val);
78 void Usage();
79
80 void OnTimeout(ProtoTimer& theTimer);
81
82 ProtoTimer the_timer;
83
84 bool first_timeout;
85 unsigned long timeout_count;
86 double ave_sum;
87 double squ_sum;
88 double delta_min;
89 double delta_max;
90 double elapsed_sec;
91
92 Histogram histogram;
93
94 unsigned int report_count;
95 int timer_int_count;
96 struct timeval last_time;
97
98 FILE* out_file;
99
100
101 bool use_nanosleep;
102
103
104 }; // end class TimerTestApp
105
106 void TimerTestApp::Usage()
107 {
108 fprintf(stderr, "Usage: timerTest [help][precise][interval <timerInterval>][output <outFile>][timer_int_count <5secIntervalCount>]\n");
109 }
110
111 const char* const TimerTestApp::CMD_LIST[] =
112 {
113 "-help", // print help info an exit
114 "+interval", // <timerInterval>
115 "-nanosleep", // Linux only
116 "-priority",
117 "-precise",
118 "+output",
119 "+timer_int_count", // number of 5 second report intervals
120 "+debug", // <debugLevel>
121 NULL
122 };
123
124 /**
125 * This macro creates our ProtoApp derived application instance
126 */
127 PROTO_INSTANTIATE_APP(TimerTestApp)
128
129 TimerTestApp::TimerTestApp()
130 : first_timeout(true), report_count(0), timer_int_count(4), out_file(stdout)
131 {
132 the_timer.SetListener(this, &TimerTestApp::OnTimeout);
133 the_timer.SetInterval(1.0);
134 the_timer.SetRepeat(-1);
135 }
136
137 TimerTestApp::~TimerTestApp()
138 {
139 }
140
141 TimerTestApp::CmdType TimerTestApp::GetCmdType(const char* cmd)
142 {
143 if (!cmd) return CMD_INVALID;
144 unsigned int len = strlen(cmd);
145 bool matched = false;
146 CmdType type = CMD_INVALID;
147 const char* const* nextCmd = CMD_LIST;
148 while (*nextCmd)
149 {
150 if (!strncmp(cmd, *nextCmd+1, len))
151 {
152 if (matched)
153 {
154 // ambiguous command (command should match only once)
155 return CMD_INVALID;
156 }
157 else
158 {
159 matched = true;
160 if ('+' == *nextCmd[0])
161 type = CMD_ARG;
162 else
163 type = CMD_NOARG;
164 }
165 }
166 nextCmd++;
167 }
168 return type;
169 } // end TimerTestApp::GetCmdType()
170
171 #ifdef WIN32
172 typedef NTSTATUS(CALLBACK* LPFN_NtQueryTimerResolution)(PULONG, PULONG, PULONG);
173 #endif // WIN32
174
175 bool TimerTestApp::OnStartup(int argc, const char*const* argv)
176 {
177
178 #if defined(USE_TIMERFD)
179 TRACE("USE_TIMERFD\n");
180 #endif
181 #if defined(USE_SELECT)
182 TRACE("USE_SELECT\n");
183 #endif
184 #if defined(HAVE_PSELECT)
185 TRACE("HAVE_PSELECT\n");
186 #endif
187 #if defined(USE_EPOLL)
188 TRACE("USE_EPOLL\n");
189 #endif
190 #ifdef USE_WAITABLE_TIMER
191 TRACE("USE_WAITABLE_TIMER\n");
192 #endif
193 #ifdef WIN32
194 HMODULE hNtDll = ::GetModuleHandle("Ntdll");
195 if (hNtDll)
196 {
197 ULONG nMinRes, nMaxRes, nCurRes;
198 LPFN_NtQueryTimerResolution pQueryResolution =
199 (LPFN_NtQueryTimerResolution)::GetProcAddress(hNtDll, "NtQueryTimerResolution");
200 if (NULL != pQueryResolution)
201 {
202 pQueryResolution(&nMinRes, &nMaxRes, &nCurRes);
203 TRACE("Windows system timer resolutions (min/max/cur): %u.%u / %u.%u / %u.%u msec\n",
204 nMinRes / 10000, (nMinRes % 10000) / 10,
205 nMaxRes / 10000, (nMaxRes % 10000) / 10,
206 nCurRes / 10000, (nCurRes % 10000) / 10);
207 /* Eventually use this to set higher resolution
208 LPFN_NtSetTimerResolution pSetResolution =
209 (LPFN_NtSetTimerResolution)::GetProcAddress(hNtDll, "NtSetTimerResolution");
210 if (pSetResolution && nSetRes)
211 {
212 NTSTATUS nStatus = pSetResolution(nSetRes, TRUE, &nCurRes);
213 }
214 */
215 }
216 }
217 #endif // WIN32
218
219 if (!ProcessCommands(argc, argv))
220 {
221 return false;
222 }
223
224 histogram.Init(1000, 1.0);
225
226 #ifdef LINUX
227 if (use_nanosleep)
228 {
229 struct timespec tspec;
230 double interval = the_timer.GetInterval();
231 tspec.tv_sec = (unsigned long)interval;
232 tspec.tv_nsec = (unsigned long)(1.0e+09 * (interval - (double)tspec.tv_sec));
233 while (1)
234 {
235 OnTimeout(the_timer);
236 if (0 != clock_nanosleep(CLOCK_MONOTONIC, 0, &tspec, NULL))
237 {
238 if (EINTR == errno)
239 {
240 TRACE("timerTest error: clock_nanosleep() EINTR error: %s\n", GetErrorString());
241
242 }
243 else
244 {
245 TRACE("timerTest error: clock_nanosleep() error: %s\n", GetErrorString());
246 break;
247 }
248 }
249 }
250 return true;
251 }
252 else
253 #endif // LINUX
254 {
255 ActivateTimer(the_timer);
256 }
257
258 return true;
259 } // end TimerTestApp::OnStartup()
260
261 void TimerTestApp::OnShutdown()
262 {
263 histogram.Print(out_file);
264 if (stdout != out_file)
265 {
266 fclose(out_file);
267 out_file = stdout;
268 }
269 PLOG(PL_ERROR, "timerTest: Done.\n");
270 } // end TimerTestApp::OnShutdown()
271
272 bool TimerTestApp::ProcessCommands(int argc, const char*const* argv)
273 {
274 // Dispatch command-line commands to our OnCommand() method
275 int i = 1;
276 while ( i < argc)
277 {
278 // Is it a timerTest command?
279 switch (GetCmdType(argv[i]))
280 {
281 case CMD_INVALID:
282 {
283 PLOG(PL_ERROR, "TimerTestApp::ProcessCommands() Invalid command:%s\n",
284 argv[i]);
285 Usage();
286 return false;
287 }
288 case CMD_NOARG:
289 if (!OnCommand(argv[i], NULL))
290 {
291 PLOG(PL_ERROR, "TimerTestApp::ProcessCommands() ProcessCommand(%s) error\n",
292 argv[i]);
293 Usage();
294 return false;
295 }
296 i++;
297 break;
298 case CMD_ARG:
299 if (!OnCommand(argv[i], argv[i+1]))
300 {
301 PLOG(PL_ERROR, "TimerTestApp::ProcessCommands() ProcessCommand(%s, %s) error\n",
302 argv[i], argv[i+1]);
303 Usage();
304 return false;
305 }
306 i += 2;
307 break;
308 }
309 }
310 return true;
311 } // end TimerTestApp::ProcessCommands()
312
313 bool TimerTestApp::OnCommand(const char* cmd, const char* val)
314 {
315 // (TBD) move command processing into Mgen class ???
316 CmdType type = GetCmdType(cmd);
317 ASSERT(CMD_INVALID != type);
318 size_t len = strlen(cmd);
319 if ((CMD_ARG == type) && !val)
320 {
321 PLOG(PL_ERROR, "TimerTestApp::ProcessCommand(%s) missing argument\n", cmd);
322 Usage();
323 return false;
324 }
325 else if (!strncmp("help", cmd, len))
326 {
327 Usage();
328 exit(0);
329 }
330 else if (!strncmp("nanosleep", cmd, len))
331 {
332 use_nanosleep = true;
333 }
334 else if (!strncmp("priority", cmd, len))
335 {
336 dispatcher.SetPriorityBoost(true);
337 dispatcher.BoostPriority();
338 }
339 else if (!strncmp("precise", cmd, len))
340 {
341 dispatcher.SetPreciseTiming(true);
342 }
343 else if (!strncmp("interval", cmd, len))
344 {
345 float timerInterval;
346 if (1 != sscanf(val, "%e", &timerInterval))
347 {
348 PLOG(PL_ERROR, "TimerTestApp::OnCommand(interval) error: invalid argument\n");
349 return false;
350 }
351 the_timer.SetInterval((double)timerInterval);
352 }
353 else if (!strncmp("timer_int_count", cmd, len))
354 {
355 int inCount;
356 if (1 != sscanf(val, "%d", &inCount))
357 {
358 PLOG(PL_ERROR, "TimerTestApp::OnCommand(count) error: invalid argument\n",GetErrorString());
359 return false;
360 }
361 timer_int_count = inCount;
362 }
363 else if (!strncmp("output", cmd, len))
364 {
365 FILE* file = fopen(val, "w+");
366 if (NULL == file)
367 {
368 PLOG(PL_ERROR, "TimerTestApp::OnCommand(interval) fopen() error: %s\n", GetErrorString());
369 return false;
370 }
371 out_file = file;
372 }
373 else if (!strncmp("debug", cmd, len))
374 {
375 SetDebugLevel(atoi(val));
376 }
377 else
378 {
379 PLOG(PL_ERROR, "timerTest error: invalid command\n");
380 Usage();
381 return false;
382 }
383 return true;
384 } // end TimerTestApp::OnCommand()
385
386
387 void TimerTestApp::OnTimeout(ProtoTimer& /*theTimer*/)
388 {
389 struct timeval currentTime;
390 ProtoSystemTime(currentTime);
391 if (first_timeout)
392 {
393 first_timeout = false;
394 elapsed_sec = 0.0;
395 ave_sum = 0.0;
396 squ_sum = 0.0;
397 timeout_count = 0;
398 delta_min = 1000.0;
399 delta_max = 0.0;
400 }
401 else
402 {
403 double delta = currentTime.tv_sec - last_time.tv_sec;
404 delta += 1.0e-06 * (currentTime.tv_usec - last_time.tv_usec);
405
406 histogram.Tally(delta);
407
408 if (delta > delta_max)
409 delta_max = delta;
410 if (delta < delta_min)
411 delta_min = delta;
412
413 elapsed_sec += delta;
414 timeout_count++;
415
416 ave_sum += delta;
417 squ_sum += (delta *delta);
418
419 if (elapsed_sec > 5.0)
420 {
421 double ave = ave_sum / timeout_count;
422 double var = (squ_sum - (ave_sum * ave)) / timeout_count;
423
424 TRACE("timer interval: ave>%lf min>%lf max>%lf var>%lf\n",
425 ave, delta_min, delta_max, var);
426 elapsed_sec = 0.0;
427 if (timer_int_count == ++report_count) Stop();
428
429 }
430 }
431 last_time = currentTime;
432 } // end TimerTestApp::OnTimeout()
433
434
435 ////////////////////////////////////////////////////////////////////
436 //
437 // Histogram implementation
438 //
439
440 Histogram::Histogram()
441 : q(1.0), num_bins(1000), min_val(0.0), max_val(0.0), bin(NULL)
442 {
443 }
444
445 /** This method creates an empty histogram with a preset
446 * value range. This is useful for outputting
447 * equivalent histgrams for multiplots
448 */
449 bool Histogram::InitBins(double rangeMin, double rangeMax)
450 {
451 if (bin) delete[] bin;
452 if (!(bin = new Bin[num_bins]))
453 {
454 perror("hcat: Histogram::InitBins() Error allocating bins");
455 return false;
456 }
457 memset(bin, 0, num_bins*sizeof(Bin));
458 min_val = rangeMin;
459 max_val = rangeMax;
460 return true;
461 } // end Histogram::InitBins()
462
463 bool Histogram::Tally(double value, unsigned long count)
464 {
465 if (!bin)
466 {
467 if (!(bin = new Bin[num_bins]))
468 {
469 perror("trpr: Histogram::Tally() Error allocating histogram");
470 return false;
471 }
472 memset(bin, 0, num_bins*sizeof(Bin));
473 min_val = max_val = value;
474 bin[0].count = count;
475 bin[0].total = (value * (double)count);
476 }
477 else if ((value > max_val) || (value < min_val))
478 {
479 Bin* newBin = new Bin[num_bins];
480 if (!newBin)
481 {
482 perror("trpr: Histogram::Tally() Error reallocating histogram");
483 return false;
484 }
485 memset(newBin, 0, num_bins*sizeof(Bin));
486
487 double newScale, minVal;
488 if (value < min_val)
489 {
490 newScale = ((double)(num_bins-1)) / pow(max_val - value, q);
491 minVal = value;
492 }
493 else
494 {
495 double s = (value < 0.0) ? 0.5 : 2.0;
496 newScale = ((double)(num_bins-1)) / pow(s*value - min_val, q);
497 minVal = min_val;
498 }
499
500 // Copy old histogram bins into new bins
501 for (unsigned int i = 0; i < num_bins; i++)
502 {
503 if (bin[i].count)
504 {
505 double x = bin[i].total / ((double)bin[i].count);
506 unsigned long index = (unsigned long)ceil(newScale * pow(x - minVal, q));
507 if (index > (num_bins-1)) index = num_bins - 1;
508 newBin[index].count += bin[i].count;
509 newBin[index].total += bin[i].total;
510 }
511 }
512
513
514 if (value < min_val)
515 {
516 newBin[0].count += count;
517 newBin[0].total += (value * (double)count);
518 min_val = value;
519 }
520 else
521 {
522 double s = (value < 0.0) ? 0.5 : 2.0;
523 max_val = s*value;
524 unsigned long index =
525 (unsigned long)ceil(((double)(num_bins-1)) * pow((value-min_val)/(max_val-min_val), q));
526 if (index > (num_bins-1)) index = num_bins - 1;
527 newBin[index].count += count;
528 newBin[index].total += (value * (double)count);
529 }
530 delete[] bin;
531 bin = newBin;
532 }
533 else
534 {
535 unsigned long index =
536 (unsigned long)ceil(((double)(num_bins-1)) * pow((value-min_val)/(max_val-min_val), q));
537 if (index > (num_bins-1)) index = num_bins - 1;
538 bin[index].count += count;
539 bin[index].total += (value * (double)count);
540 }
541 return true;
542 } // end Histogram::Tally()
543
544 void Histogram::Print(FILE* file, bool showAll)
545 {
546 if (bin)
547 {
548 for (unsigned int i = 0; i < num_bins; i++)
549 {
550 if ((0 != bin[i].count) || showAll)
551 {
552 fprintf(file, "%f, %lu\n", GetBinValue(i), bin[i].count);
553 }
554 }
555 }
556 } // end Histogram::Print()
557
558
559 unsigned long Histogram::Count()
560 {
561 if (bin)
562 {
563 unsigned long total = 0 ;
564 for (unsigned int i = 0; i < num_bins; i++)
565 {
566 total += bin[i].count;
567 }
568 return total;
569 }
570 else
571 {
572 return 0;
573 }
574 } // end Histogram::Count()
575
576 double Histogram::PercentageInRange(double rangeMin, double rangeMax)
577 {
578 if (bin)
579 {
580 unsigned long countTotal = 0;
581 unsigned long rangeTotal = 0;
582 for (unsigned long i = 0; i < num_bins; i++)
583 {
584 if (bin[i].count)
585 {
586 double value = bin[i].total / ((double)bin[i].count);
587 countTotal += bin[i].count;
588 if (value < rangeMin)
589 continue;
590 else if (value > rangeMax)
591 continue;
592 else
593 rangeTotal += bin[i].count;
594 }
595 }
596 return (100.0 * ((double)rangeTotal) / ((double)countTotal));
597 }
598 else
599 {
600 return 0.0;
601 }
602 } // end Histogram::PercentageInRange()
603
604 unsigned long Histogram::CountInRange(double rangeMin, double rangeMax)
605 {
606 if (bin)
607 {
608 unsigned long rangeTotal = 0;
609 for (unsigned long i = 0; i < num_bins; i++)
610 {
611 if (bin[i].count)
612 {
613 double value = bin[i].total / ((double)bin[i].count);
614 if (value < rangeMin)
615 continue;
616 else if (value > rangeMax)
617 break;
618 else
619 rangeTotal += bin[i].count;
620 }
621 }
622 return rangeTotal;
623 }
624 else
625 {
626 return 0;
627 }
628 } // end Histogram::CountInRange()
629
630
631 double Histogram::Percentile(double p)
632 {
633 unsigned long goal = Count();
634 goal = (unsigned long)(((double)goal) * p + 0.5);
635 unsigned long count = 0;
636 if (bin)
637 {
638 for (unsigned long i = 0; i < num_bins; i++)
639 {
640 count += bin[i].count;
641 if (count >= goal)
642 {
643 double x = pow(((double)i) / ((double)num_bins-1), 1.0/q);
644 x *= (max_val - min_val);
645 x += min_val;
646 return x;
647 }
648 }
649 }
650 return max_val;
651 } // end Histogram::Percentile()
652
653