softwarecontainer  0.18.0-739e8d7 2017-05-04
ivi-profiling.h
1 /*
2  * Copyright (C) 2016-2017 Pelagicore AB
3  *
4  * Permission to use, copy, modify, and/or distribute this software for
5  * any purpose with or without fee is hereby granted, provided that the
6  * above copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
9  * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
10  * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
11  * BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
12  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
13  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
14  * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
15  * SOFTWARE.
16  *
17  * For further information see LICENSE
18  */
19 
20 
21 
22 #pragma once
23 
24 #include <ivi-logging.h>
25 #include <iostream>
26 #include <time.h>
27 #include <iomanip>
28 
29 typedef logging::DefaultLogContext LogContext;
30 
31 // Profile a single point in time.
32 #ifdef PROFILING_ENABLED
33 #define profilepoint(s) \
34  PProfiler::point(s);
35 #else // PROFILING_ENABLED
36 #define profilepoint(s)
37 #endif
38 
39 // If profiling is enabled, create an instance of Profiler. This will be
40 // destroyed when leaving scope
41 #ifdef PROFILING_ENABLED
42 #define profilefunction(s) \
43  PProfiler prof(s);
44 #else // PROFILING_ENABLED
45 #define profilefunction(s)
46 #endif
47 
48 class PProfiler {
49 public:
50  LOG_DECLARE_CLASS_CONTEXT("PPRO", "Profiler context");
51 
52  PProfiler(std::string s) {
53  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &m_time1);
54  log_warn() << "profiler " << s << " start " << format(m_time1);
55  m_s = s;
56  };
57 
58  ~PProfiler() {
59  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &m_time2);
60  timespec d = diff(m_time1, m_time2);
61  log_warn() << "profiler " << m_s << " end " << format(m_time2) << " " << format(d);
62  };
63 
64  static void point(std::string s)
65  {
66  timespec t;
67  clock_gettime(CLOCK_REALTIME, &t);
68  log_warn() << "profilerPoint " << s << " " << PProfiler::format(t);
69  }
70 
71  static std::string format(timespec t)
72  {
73  std::stringstream ss;
74  ss << std::setfill('0') << std::setw(1) << t.tv_sec << "." << std::setw(9) << t.tv_nsec;
75  return ss.str();
76  }
77 
78  timespec diff(timespec start, timespec end)
79  {
80  timespec temp;
81  if ((end.tv_nsec-start.tv_nsec)<0) {
82  temp.tv_sec = end.tv_sec-start.tv_sec-1;
83  temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
84  } else {
85  temp.tv_sec = end.tv_sec-start.tv_sec;
86  temp.tv_nsec = end.tv_nsec-start.tv_nsec;
87  }
88  return temp;
89  }
90 
91 private:
92  std::string m_s;
93  timespec m_time1, m_time2;
94 };