aboutsummaryrefslogtreecommitdiff
path: root/samples/timestamp.cc
blob: 50c65393e9fb7b89d1b8764749a9f275b89b55bc (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
// Copyright 2019 The Amber Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "samples/timestamp.h"

#include <cassert>

#if defined(_WIN32) || defined(_WIN64)
#define SAMPLE_PLATFORM_WINDOWS 1
#define SAMPLE_PLATFORM_POSIX 0
#elif defined(__linux__) || defined(__APPLE__)
#define SAMPLE_PLATFORM_POSIX 1
#define SAMPLE_PLATFORM_WINDOWS 0
#endif

#if SAMPLE_PLATFORM_WINDOWS
#include <windows.h>
#elif SAMPLE_PLATFORM_POSIX
#include <time.h>
#else
#error "Unknown platform"
#endif

namespace timestamp {

uint64_t SampleGetTimestampNs() {
  uint64_t timestamp = 0;

#if SAMPLE_PLATFORM_WINDOWS

  LARGE_INTEGER tick_per_seconds;
  if (!QueryPerformanceFrequency(&tick_per_seconds)) {
    return 0;
  }
  LARGE_INTEGER ticks;
  if (!QueryPerformanceCounter(&ticks)) {
    return 0;
  }
  double tick_duration_ns = static_cast<double>(1.0e9) /
                            static_cast<double>(tick_per_seconds.QuadPart);
  timestamp = uint64_t(static_cast<double>(ticks.QuadPart) * tick_duration_ns);

#elif SAMPLE_PLATFORM_POSIX

  struct timespec time;
  if (clock_gettime(CLOCK_MONOTONIC, &time)) {
    return 0;
  }
  timestamp = static_cast<uint64_t>((time.tv_sec * 1000000000) + time.tv_nsec);

#else
#error "Implement timestamp::SampleGetTimestampNs"
#endif

  return timestamp;
}

}  // namespace timestamp