summaryrefslogtreecommitdiff
path: root/graphics/asymptote/seconds.h
blob: b42e69216965df380aceb2c1214271f6f35ae0f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#ifndef __seconds_h__
#define __seconds_h__ 1

#include <chrono>
#include <sys/resource.h>

namespace utils {

#ifdef _WIN32
#include <Windows.h>
#define getpid GetCurrentProcessId
inline double cpuTime() {
  FILETIME a,b,c,d;
  return GetProcessTimes(GetCurrentThread(),&a,&b,&c,&d) != 0 ?
    (double) (d.dwLowDateTime |
              ((unsigned long long)d.dwHighDateTime << 32))*100.0 : 0.0;
}
#else
#include <unistd.h>
#include <time.h>

inline double cpuTime() {
#ifdef CLOCK_THREAD_CPUTIME_ID
#define GETTIME_ID CLOCK_THREAD_CPUTIME_ID
#elif defined(CLOCK_PROCESS_CPUTIME_ID)
#define GETTIME_ID CLOCK_PROCESS_CPUTIME_ID
#endif

#ifdef GETTIME_ID
  timespec t;
  clock_gettime(GETTIME_ID,&t);
  return 1.0e9*t.tv_sec+t.tv_nsec;
#undef GETTIME_ID
#else
  struct rusage ru;
  if(getrusage(RUSAGE_SELF, &ru))
    return 0;
  return 1.0e9*(ru.ru_utime.tv_sec+ru.ru_stime.tv_sec)
    +1.0e3*(ru.ru_utime.tv_usec+ru.ru_stime.tv_usec);
#endif
}
#endif

class stopWatch {
  std::chrono::time_point<std::chrono::steady_clock> Start;

public:
  void reset() {
    Start=std::chrono::steady_clock::now();
  }

  stopWatch() {
    reset();
  }

  double nanoseconds(bool reset=false) {
    auto Stop=std::chrono::steady_clock::now();
    double ns=std::chrono::duration_cast<std::chrono::nanoseconds>
      (Stop-Start).count();
    if(reset)
      Start=Stop;
    return ns;
  }

  double seconds(bool reset=false) {
    return 1.0e-9*nanoseconds(reset);
  }
};

class cpuTimer {
  double start;
  std::chrono::time_point<std::chrono::steady_clock> Start;

public:
  void reset() {
    start=cpuTime();
    Start=std::chrono::steady_clock::now();
  }

  cpuTimer() {
    reset();
  }

  double nanoseconds(bool reset=false) {
    auto Stop=std::chrono::steady_clock::now();
    double stop=cpuTime();
    double ns=std::min((double) std::chrono::duration_cast<std::chrono::nanoseconds>
                       (Stop-Start).count(),stop-start);
    if(reset) {
      Start=Stop;
      start=stop;
    }
    return ns;
  }

  double seconds(bool reset=false) {
    return 1.0e-9*nanoseconds(reset);
  }
};

}

#endif