iotivity 0.9.0
[platform/upstream/iotivity.git] / resource / examples / ocicuc / utility.cpp
1 #include <chrono>
2 #include <string>
3 #include <iostream>
4 #include <algorithm>
5
6 #include "utility.hpp"
7
8 namespace Intel { namespace OCDemo {
9
10 int observe_count()
11 {
12  static unsigned long long oc = 0;
13  return ++oc;
14 }
15
16 }} // namespace Intel::OCDemo
17
18 // Helper for measuring call times:
19 namespace Intel { namespace OCDemo {
20
21 using std::cout;
22 using namespace std::chrono;
23
24 call_times call_timer;
25
26 void call_times::reset(const std::string& entry) 
27
28  timings[entry] = make_pair(high_resolution_clock::now(), std::chrono::high_resolution_clock::time_point()); 
29 }
30
31 void call_times::mark(const std::string& name)
32 {
33  auto e = timings.find(name);
34
35     if(timings.end() == e)
36      {
37         reset(name);
38         return;
39      }
40
41     auto& tp = (*e).second;
42
43     if(tp.first > tp.second)
44      timings[name].second = high_resolution_clock::now();
45   }
46
47 void call_times::report()
48 {
49  cout << "Time marks:\n";
50
51  for_each(begin(timings), end(timings), 
52  [](const std::pair<std::string, clock_interval>& tm) -> void 
53  {
54     const std::string& name     { tm.first };
55
56     const time_point<high_resolution_clock>& request_time    { tm.second.first };
57     const time_point<high_resolution_clock>& response_time   { tm.second.second };
58
59     cout << '\t' << name << ": ";
60
61     if(request_time > response_time)
62      {
63         cout << "<waiting>\n";
64         return;
65      }
66
67     auto elapsed_ms = duration_cast<std::chrono::milliseconds>(response_time - request_time).count();
68     cout << elapsed_ms << "ms (";
69
70     auto elapsed_us = duration_cast<std::chrono::microseconds>(response_time - request_time).count();
71     cout << elapsed_us << "us)\n";
72  });
73 }
74
75 void call_times::report_and_reset(const std::string& name)
76 {
77  mark(name), report(), reset(name);
78 }
79
80
81 }} // namespace Intel::OCDemo