1 // Copyright 2019 The Amber Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "samples/timestamp.h"
16 
17 #include <cassert>
18 
19 #if defined(_WIN32) || defined(_WIN64)
20 #define SAMPLE_PLATFORM_WINDOWS 1
21 #define SAMPLE_PLATFORM_POSIX 0
22 #elif defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__)
23 #define SAMPLE_PLATFORM_POSIX 1
24 #define SAMPLE_PLATFORM_WINDOWS 0
25 #endif
26 
27 #if SAMPLE_PLATFORM_WINDOWS
28 #include <windows.h>
29 #elif SAMPLE_PLATFORM_POSIX
30 #include <time.h>
31 #else
32 #error "Unknown platform"
33 #endif
34 
35 namespace timestamp {
36 
SampleGetTimestampNs()37 uint64_t SampleGetTimestampNs() {
38   uint64_t timestamp = 0;
39 
40 #if SAMPLE_PLATFORM_WINDOWS
41 
42   LARGE_INTEGER tick_per_seconds;
43   if (!QueryPerformanceFrequency(&tick_per_seconds)) {
44     return 0;
45   }
46   LARGE_INTEGER ticks;
47   if (!QueryPerformanceCounter(&ticks)) {
48     return 0;
49   }
50   double tick_duration_ns = static_cast<double>(1.0e9) /
51                             static_cast<double>(tick_per_seconds.QuadPart);
52   timestamp = uint64_t(static_cast<double>(ticks.QuadPart) * tick_duration_ns);
53 
54 #elif SAMPLE_PLATFORM_POSIX
55 
56   struct timespec time;
57   if (clock_gettime(CLOCK_MONOTONIC, &time)) {
58     return 0;
59   }
60   timestamp = static_cast<uint64_t>((time.tv_sec * 1000000000) + time.tv_nsec);
61 
62 #else
63 #error "Implement timestamp::SampleGetTimestampNs"
64 #endif
65 
66   return timestamp;
67 }
68 
69 }  // namespace timestamp
70