automatic commit
[folded-ctf.git] / chrono.cc
diff --git a/chrono.cc b/chrono.cc
new file mode 100644 (file)
index 0000000..c4b7267
--- /dev/null
+++ b/chrono.cc
@@ -0,0 +1,62 @@
+
+///////////////////////////////////////////////////////////////////////////
+// This program is free software: you can redistribute it and/or modify  //
+// it under the terms of the version 3 of the GNU General Public License //
+// as published by the Free Software Foundation.                         //
+//                                                                       //
+// This program is distributed in the hope that it will be useful, but   //
+// WITHOUT ANY WARRANTY; without even the implied warranty of            //
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      //
+// General Public License for more details.                              //
+//                                                                       //
+// You should have received a copy of the GNU General Public License     //
+// along with this program. If not, see <http://www.gnu.org/licenses/>.  //
+//                                                                       //
+// Written by Francois Fleuret, (C) IDIAP                                //
+// Contact <francois.fleuret@idiap.ch> for comments & bug reports        //
+///////////////////////////////////////////////////////////////////////////
+
+#include <string.h>
+
+#include "chrono.h"
+
+Chrono::Chrono() : _nb_ticks_per_second(scalar_t(sysconf(_SC_CLK_TCK))),
+                   _nb(0), _current(-1) { }
+
+void Chrono::print(ostream *os) {
+  scalar_t total_durations = 0;
+  for(int n = 0; n < _nb; n++) total_durations += _durations[n];
+  for(int n = 0; n < _nb; n++)
+    (*os) << "INFO CHRONO_" << _labels[n]
+          << " " << scalar_t(_durations[n] * 100) / total_durations << "%"
+          << " " << _durations[n] << " seconds"
+          << endl;
+}
+
+void Chrono::start(const char *label) {
+  if(_current >= 0) {
+    struct tms tmp;
+    times(&tmp);
+    _durations[_current] += scalar_t(tmp.tms_stime - _last.tms_stime)/_nb_ticks_per_second;
+  }
+
+  if(label) {
+    _current = 0;
+    while(_current < _nb && strcmp(_labels[_current], label) != 0)
+      _current++;
+    if(_current == _nb) {
+      if(_nb < _nb_max) {
+        strncpy(_labels[_nb], label, buffer_size);
+        _durations[_nb] = 0;
+        _nb++;
+      } else {
+        cerr << "Too many timers." << endl;
+        exit(1);
+      }
+    }
+  } else _current = -1;
+
+  times(&_last);
+}
+
+void Chrono::stop() { start(0); }