pinocchio  2.3.1-dirty
timer.hpp
1 //
2 // Copyright (c) 2015-2019 CNRS INRIA
3 //
4 
5 #ifndef __pinocchio_utils_timer_hpp__
6 #define __pinocchio_utils_timer_hpp__
7 
8 #include <sys/time.h>
9 #include <iostream>
10 #include <stack>
11 
12 #define SMOOTH(s) for(size_t _smooth=0;_smooth<s;++_smooth)
13 
14 /* Return the time spent in secs. */
15 inline double operator-(const struct timeval & t1,const struct timeval & t0)
16 {
17  /* TODO: double check the double conversion from long (on 64x). */
18  return double(t1.tv_sec - t0.tv_sec)+1e-6*double(t1.tv_usec - t0.tv_usec);
19 }
20 
22 {
23  enum Unit { S = 1, MS = 1000, US = 1000000, NS = 1000000000 };
24  Unit DEFAULT_UNIT;
25 
26  static std::string unitName(Unit u)
27  {
28  switch(u) { case S: return "s"; case MS: return "ms"; case US: return "us"; case NS: return "ns"; }
29  return "";
30  }
31 
32  std::stack<struct timeval> stack;
33  mutable struct timeval t0;
34 
35  PinocchioTicToc( Unit def = MS ) : DEFAULT_UNIT(def) {}
36 
37  inline void tic() {
38  stack.push(t0);
39  gettimeofday(&(stack.top()),NULL);
40  }
41 
42  inline double toc() { return toc(DEFAULT_UNIT); };
43 
44  inline double toc(const Unit factor)
45  {
46  gettimeofday(&t0,NULL);
47  double dt = (t0-stack.top())*factor;
48  stack.pop();
49  return dt;
50  }
51 
52  inline void toc(std::ostream & os, double SMOOTH=1)
53  {
54  os << toc(DEFAULT_UNIT)/SMOOTH << " " << unitName(DEFAULT_UNIT) << std::endl;
55  }
56 };
57 
58 #endif // ifndef __pinocchio_utils_timer_hpp__