PetaVision  Alpha
Timer.cpp
1 /*
2  * Timer.cpp
3  * opencl
4  *
5  * Created by Craig Rasmussen on 11/15/09.
6  * Copyright 2009 Los Alamos National Laboratory. All rights reserved.
7  *
8  */
9 
10 #include "Timer.hpp"
11 #include "utils/PVLog.hpp"
12 #include <stdio.h>
13 
14 #ifdef __APPLE__
15 #define USE_MACH_TIMER
16 #endif
17 
18 #ifdef USE_MACH_TIMER
19 //# include <CoreServices/CoreServices.h>
20 #include <mach/mach.h>
21 #include <mach/mach_time.h>
22 #else
23 #include <sys/time.h>
24 #endif // USE_MACH_TIMER
25 
29 uint64_t get_cpu_time() {
30 #ifdef USE_MACH_TIMER
31  return mach_absolute_time();
32 #else
33  struct timeval tim;
34  gettimeofday(&tim, NULL);
35  return ((uint64_t)tim.tv_sec) * 1000000 + (uint64_t)tim.tv_usec;
36 #endif
37 }
38 
39 // Convert to milliseconds
40 static double cpu_time_to_sec(uint64_t cpu_elapsed) {
41  double us = 0.0;
42 #ifdef USE_MACH_TIMER
43  static mach_timebase_info_data_t info;
44  mach_timebase_info(&info);
45  cpu_elapsed *= info.numer;
46  cpu_elapsed /= info.denom;
47  us = (double)(cpu_elapsed / 1000); // microseconds
48 #else
49  us = (double)cpu_elapsed;
50 #endif
51  return us / 1000.0;
52 }
53 
54 namespace PV {
55 
56 Timer::Timer(double init_time) {
57  rank = 0;
58  reset(init_time);
59  message = strdup("");
60 }
61 
62 Timer::Timer(const char *timermessage, double init_time) {
63  rank = 0;
64  reset(init_time);
65  message = strdup(timermessage ? timermessage : "");
66 }
67 
68 Timer::Timer(const char *objname, const char *objtype, const char *timertype, double init_time) {
69  rank = 0;
70  reset(init_time);
71  char dummy;
72  int charsneeded =
73  snprintf(&dummy, 1, "%32s: total time in %6s %10s: ", objname, objtype, timertype);
74  message = (char *)malloc(charsneeded + 1);
75  if (message == NULL) {
76  Fatal().printf(
77  "Timer::setMessage unable to allocate memory for Timer message: called with name=%s, "
78  "objtype=%s, timertype=%s\n",
79  objname,
80  objtype,
81  timertype);
82  }
83  int chars_used = snprintf(
84  message, charsneeded + 1, "%32s: total time in %6s %10s: ", objname, objtype, timertype);
85  assert(chars_used <= charsneeded);
86 }
87 
88 Timer::~Timer() { free(message); }
89 
90 void Timer::reset(double init_time) {
91  time_start = get_cpu_time();
92  time_end = time_start;
93  time_elapsed = init_time;
94 }
95 
96 double Timer::start() { return (double)(time_start = get_cpu_time()); }
97 
98 double Timer::stop() {
99  time_end = get_cpu_time();
100  time_elapsed += time_end - time_start;
101  return (double)time_end;
102 }
103 
104 double Timer::elapsed_time() const { return (double)time_elapsed; }
105 
106 int Timer::fprint_time(PrintStream &stream) const {
107  if (rank == 0) {
108  stream << message << "processor cycle time == " << (float)cpu_time_to_sec(elapsed_time())
109  << std::endl;
110  }
111  return 0;
112 }
113 
114 } // namespace PV