PageRenderTime 46ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/Software/Source/LibOVRKernel/Src/Kernel/OVR_Timer.cpp

https://gitlab.com/jensclae/Bachelorproef_JensClaes_3MMP_ProDuce
C++ | 460 lines | 278 code | 104 blank | 78 comment | 36 complexity | 592f7922fcd357f5c9a669b61c6d3ce5 MD5 | raw file
  1. /************************************************************************************
  2. Filename : OVR_Timer.cpp
  3. Content : Provides static functions for precise timing
  4. Created : September 19, 2012
  5. Notes :
  6. Copyright : Copyright 2014 Oculus VR, LLC All Rights reserved.
  7. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
  8. you may not use the Oculus VR Rift SDK except in compliance with the License,
  9. which is provided at the time of installation or download, or which
  10. otherwise accompanies this software in either electronic or hard copy form.
  11. You may obtain a copy of the License at
  12. http://www.oculusvr.com/licenses/LICENSE-3.2
  13. Unless required by applicable law or agreed to in writing, the Oculus VR SDK
  14. distributed under the License is distributed on an "AS IS" BASIS,
  15. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. See the License for the specific language governing permissions and
  17. limitations under the License.
  18. ************************************************************************************/
  19. #include "OVR_Timer.h"
  20. #include "OVR_Log.h"
  21. #if defined(OVR_OS_MS) && !defined(OVR_OS_MS_MOBILE)
  22. #include "OVR_Win32_IncludeWindows.h"
  23. #include <MMSystem.h>
  24. #pragma comment(lib, "winmm.lib")
  25. #elif defined(OVR_OS_ANDROID)
  26. #include <time.h>
  27. #include <android/log.h>
  28. #else
  29. #include <chrono>
  30. #endif
  31. #if defined(OVR_BUILD_DEBUG) && defined(OVR_OS_WIN32)
  32. typedef NTSTATUS (NTAPI* NtQueryTimerResolutionType)(PULONG MaximumTime, PULONG MinimumTime, PULONG CurrentTime);
  33. NtQueryTimerResolutionType pNtQueryTimerResolution;
  34. #endif
  35. #if defined(OVR_OS_MS) && !defined(OVR_OS_WIN32) // Non-desktop Microsoft platforms...
  36. // Add this alias here because we're not going to include OVR_CAPI.cpp
  37. extern "C" {
  38. double ovr_GetTimeInSeconds()
  39. {
  40. return Timer::GetSeconds();
  41. }
  42. }
  43. #endif
  44. namespace OVR {
  45. // For recorded data playback
  46. bool Timer::useFakeSeconds = false;
  47. double Timer::FakeSeconds = 0;
  48. //------------------------------------------------------------------------
  49. // *** Android Specific Timer
  50. #if defined(OVR_OS_ANDROID) // To consider: This implementation can also work on most Linux distributions
  51. //------------------------------------------------------------------------
  52. // *** Timer - Platform Independent functions
  53. // Returns global high-resolution application timer in seconds.
  54. double Timer::GetSeconds()
  55. {
  56. if(useFakeSeconds)
  57. return FakeSeconds;
  58. // Choreographer vsync timestamp is based on.
  59. struct timespec tp;
  60. const int status = clock_gettime(CLOCK_MONOTONIC, &tp);
  61. #ifdef OVR_BUILD_DEBUG
  62. if (status != 0)
  63. {
  64. OVR_DEBUG_LOG(("clock_gettime status=%i", status ));
  65. }
  66. #else
  67. OVR_UNUSED(status);
  68. #endif
  69. return (double)tp.tv_sec;
  70. }
  71. uint64_t Timer::GetTicksNanos()
  72. {
  73. if (useFakeSeconds)
  74. return (uint64_t) (FakeSeconds * NanosPerSecond);
  75. // Choreographer vsync timestamp is based on.
  76. struct timespec tp;
  77. const int status = clock_gettime(CLOCK_MONOTONIC, &tp);
  78. #ifdef OVR_BUILD_DEBUG
  79. if (status != 0)
  80. {
  81. OVR_DEBUG_LOG(("clock_gettime status=%i", status ));
  82. }
  83. #else
  84. OVR_UNUSED(status);
  85. #endif
  86. const uint64_t result = (uint64_t)tp.tv_sec * (uint64_t)(1000 * 1000 * 1000) + uint64_t(tp.tv_nsec);
  87. return result;
  88. }
  89. void Timer::initializeTimerSystem()
  90. {
  91. // Empty for this platform.
  92. }
  93. void Timer::shutdownTimerSystem()
  94. {
  95. // Empty for this platform.
  96. }
  97. //------------------------------------------------------------------------
  98. // *** Win32 Specific Timer
  99. #elif defined (OVR_OS_MS)
  100. // This helper class implements high-resolution wrapper that combines timeGetTime() output
  101. // with QueryPerformanceCounter. timeGetTime() is lower precision but drives the high bits,
  102. // as it's tied to the system clock.
  103. struct PerformanceTimer
  104. {
  105. PerformanceTimer()
  106. : UsingVistaOrLater(false),
  107. TimeCS(),
  108. OldMMTimeMs(0),
  109. MMTimeWrapCounter(0),
  110. PerfFrequency(0),
  111. PerfFrequencyInverse(0),
  112. PerfFrequencyInverseNanos(0),
  113. PerfMinusTicksDeltaNanos(0),
  114. LastResultNanos(0)
  115. { }
  116. enum {
  117. MMTimerResolutionNanos = 1000000
  118. };
  119. void Initialize();
  120. void Shutdown();
  121. uint64_t GetTimeSeconds();
  122. double GetTimeSecondsDouble();
  123. uint64_t GetTimeNanos();
  124. UINT64 getFrequency()
  125. {
  126. if (PerfFrequency == 0)
  127. {
  128. LARGE_INTEGER freq;
  129. QueryPerformanceFrequency(&freq);
  130. PerfFrequency = freq.QuadPart;
  131. PerfFrequencyInverse = 1.0 / (double)PerfFrequency;
  132. PerfFrequencyInverseNanos = 1000000000.0 / (double)PerfFrequency;
  133. }
  134. return PerfFrequency;
  135. }
  136. double GetFrequencyInverse()
  137. {
  138. OVR_ASSERT(PerfFrequencyInverse != 0.0); // Assert that the frequency has been initialized.
  139. return PerfFrequencyInverse;
  140. }
  141. bool UsingVistaOrLater;
  142. CRITICAL_SECTION TimeCS;
  143. // timeGetTime() support with wrap.
  144. uint32_t OldMMTimeMs;
  145. uint32_t MMTimeWrapCounter;
  146. // Cached performance frequency result.
  147. uint64_t PerfFrequency; // cycles per second, typically a large value like 3000000, but usually not the same as the CPU clock rate.
  148. double PerfFrequencyInverse; // seconds per cycle (will be a small fractional value).
  149. double PerfFrequencyInverseNanos; // nanoseconds per cycle.
  150. // Computed as (perfCounterNanos - ticksCounterNanos) initially,
  151. // and used to adjust timing.
  152. uint64_t PerfMinusTicksDeltaNanos;
  153. // Last returned value in nanoseconds, to ensure we don't back-step in time.
  154. uint64_t LastResultNanos;
  155. };
  156. static PerformanceTimer Win32_PerfTimer;
  157. void PerformanceTimer::Initialize()
  158. {
  159. #if defined(OVR_OS_WIN32) // Desktop Windows only
  160. // The following has the effect of setting the NT timer resolution (NtSetTimerResolution) to 1 millisecond.
  161. MMRESULT mmr = timeBeginPeriod(1);
  162. OVR_ASSERT(TIMERR_NOERROR == mmr);
  163. OVR_UNUSED(mmr);
  164. #endif
  165. InitializeCriticalSection(&TimeCS);
  166. MMTimeWrapCounter = 0;
  167. getFrequency();
  168. #if defined(OVR_OS_WIN32) // Desktop Windows only
  169. // Set Vista flag. On Vista, we can just use QPC() without all the extra work
  170. OSVERSIONINFOEX ver;
  171. ZeroMemory(&ver, sizeof(OSVERSIONINFOEX));
  172. ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  173. ver.dwMajorVersion = 6; // Vista+
  174. DWORDLONG condMask = 0;
  175. VER_SET_CONDITION(condMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
  176. // VerifyVersionInfo returns true if the OS meets the conditions set above
  177. UsingVistaOrLater = VerifyVersionInfo(&ver, VER_MAJORVERSION, condMask) != 0;
  178. #else
  179. UsingVistaOrLater = true;
  180. #endif
  181. OVR_DEBUG_LOG(("PerformanceTimer UsingVistaOrLater = %d", (int)UsingVistaOrLater));
  182. #if defined(OVR_BUILD_DEBUG) && defined(OVR_OS_WIN32)
  183. HMODULE hNtDll = LoadLibraryW(L"NtDll.dll");
  184. if (hNtDll)
  185. {
  186. pNtQueryTimerResolution = (NtQueryTimerResolutionType)GetProcAddress(hNtDll, "NtQueryTimerResolution");
  187. //pNtSetTimerResolution = (NtSetTimerResolutionType)GetProcAddress(hNtDll, "NtSetTimerResolution");
  188. if(pNtQueryTimerResolution)
  189. {
  190. ULONG MinimumResolution; // in 100-ns units
  191. ULONG MaximumResolution;
  192. ULONG ActualResolution;
  193. pNtQueryTimerResolution(&MinimumResolution, &MaximumResolution, &ActualResolution);
  194. OVR_DEBUG_LOG(("NtQueryTimerResolution = Min %ld us, Max %ld us, Current %ld us", MinimumResolution / 10, MaximumResolution / 10, ActualResolution / 10));
  195. }
  196. FreeLibrary(hNtDll);
  197. }
  198. #endif
  199. }
  200. void PerformanceTimer::Shutdown()
  201. {
  202. DeleteCriticalSection(&TimeCS);
  203. #if defined(OVR_OS_WIN32) // Desktop Windows only
  204. MMRESULT mmr = timeEndPeriod(1);
  205. OVR_ASSERT(TIMERR_NOERROR == mmr);
  206. OVR_UNUSED(mmr);
  207. #endif
  208. }
  209. uint64_t PerformanceTimer::GetTimeSeconds()
  210. {
  211. if (UsingVistaOrLater)
  212. {
  213. LARGE_INTEGER li;
  214. QueryPerformanceCounter(&li);
  215. OVR_ASSERT(PerfFrequencyInverse != 0); // Initialize should have been called earlier.
  216. return (uint64_t)(li.QuadPart * PerfFrequencyInverse);
  217. }
  218. return (uint64_t)(GetTimeNanos() * .0000000001);
  219. }
  220. double PerformanceTimer::GetTimeSecondsDouble()
  221. {
  222. if (UsingVistaOrLater)
  223. {
  224. LARGE_INTEGER li;
  225. QueryPerformanceCounter(&li);
  226. OVR_ASSERT(PerfFrequencyInverse != 0);
  227. return (li.QuadPart * PerfFrequencyInverse);
  228. }
  229. return (GetTimeNanos() * .0000000001);
  230. }
  231. uint64_t PerformanceTimer::GetTimeNanos()
  232. {
  233. uint64_t resultNanos;
  234. LARGE_INTEGER li;
  235. OVR_ASSERT(PerfFrequencyInverseNanos != 0); // Initialize should have been called earlier.
  236. if (UsingVistaOrLater) // Includes non-desktop platforms
  237. {
  238. // Then we can use QPC() directly without all that extra work
  239. QueryPerformanceCounter(&li);
  240. resultNanos = (uint64_t)(li.QuadPart * PerfFrequencyInverseNanos);
  241. }
  242. else
  243. {
  244. // On Win32 QueryPerformanceFrequency is unreliable due to SMP and
  245. // performance levels, so use this logic to detect wrapping and track
  246. // high bits.
  247. ::EnterCriticalSection(&TimeCS);
  248. // Get raw value and perf counter "At the same time".
  249. QueryPerformanceCounter(&li);
  250. DWORD mmTimeMs = timeGetTime();
  251. if (OldMMTimeMs > mmTimeMs)
  252. MMTimeWrapCounter++;
  253. OldMMTimeMs = mmTimeMs;
  254. // Normalize to nanoseconds.
  255. uint64_t perfCounterNanos = (uint64_t)(li.QuadPart * PerfFrequencyInverseNanos);
  256. uint64_t mmCounterNanos = ((uint64_t(MMTimeWrapCounter) << 32) | mmTimeMs) * 1000000;
  257. if (PerfMinusTicksDeltaNanos == 0)
  258. PerfMinusTicksDeltaNanos = perfCounterNanos - mmCounterNanos;
  259. // Compute result before snapping.
  260. //
  261. // On first call, this evaluates to:
  262. // resultNanos = mmCounterNanos.
  263. // Next call, assuming no wrap:
  264. // resultNanos = prev_mmCounterNanos + (perfCounterNanos - prev_perfCounterNanos).
  265. // After wrap, this would be:
  266. // resultNanos = snapped(prev_mmCounterNanos +/- 1ms) + (perfCounterNanos - prev_perfCounterNanos).
  267. //
  268. resultNanos = perfCounterNanos - PerfMinusTicksDeltaNanos;
  269. // Snap the range so that resultNanos never moves further apart then its target resolution.
  270. // It's better to allow more slack on the high side as timeGetTime() may be updated at sporadically
  271. // larger then 1 ms intervals even when 1 ms resolution is requested.
  272. if (resultNanos > (mmCounterNanos + MMTimerResolutionNanos*2))
  273. {
  274. resultNanos = mmCounterNanos + MMTimerResolutionNanos*2;
  275. if (resultNanos < LastResultNanos)
  276. resultNanos = LastResultNanos;
  277. PerfMinusTicksDeltaNanos = perfCounterNanos - resultNanos;
  278. }
  279. else if (resultNanos < (mmCounterNanos - MMTimerResolutionNanos))
  280. {
  281. resultNanos = mmCounterNanos - MMTimerResolutionNanos;
  282. if (resultNanos < LastResultNanos)
  283. resultNanos = LastResultNanos;
  284. PerfMinusTicksDeltaNanos = perfCounterNanos - resultNanos;
  285. }
  286. LastResultNanos = resultNanos;
  287. ::LeaveCriticalSection(&TimeCS);
  288. }
  289. //Tom's addition, to keep precision
  290. //static uint64_t initial_time = 0;
  291. //if (!initial_time) initial_time = resultNanos;
  292. //resultNanos -= initial_time;
  293. // FIXME: This cannot be used for cross-process timestamps
  294. return resultNanos;
  295. }
  296. //------------------------------------------------------------------------
  297. // *** Timer - Platform Independent functions
  298. // Returns global high-resolution application timer in seconds.
  299. double Timer::GetSeconds()
  300. {
  301. if(useFakeSeconds)
  302. return FakeSeconds;
  303. return Win32_PerfTimer.GetTimeSecondsDouble();
  304. }
  305. // Delegate to PerformanceTimer.
  306. uint64_t Timer::GetTicksNanos()
  307. {
  308. if (useFakeSeconds)
  309. return (uint64_t) (FakeSeconds * NanosPerSecond);
  310. return Win32_PerfTimer.GetTimeNanos();
  311. }
  312. // Windows version also provides the performance frequency inverse.
  313. double Timer::GetPerfFrequencyInverse()
  314. {
  315. return Win32_PerfTimer.GetFrequencyInverse();
  316. }
  317. void Timer::initializeTimerSystem()
  318. {
  319. Win32_PerfTimer.Initialize();
  320. }
  321. void Timer::shutdownTimerSystem()
  322. {
  323. Win32_PerfTimer.Shutdown();
  324. }
  325. #else // C++11 standard compliant platforms
  326. double Timer::GetSeconds()
  327. {
  328. if(useFakeSeconds)
  329. return FakeSeconds;
  330. using FpSeconds = std::chrono::duration<double, std::chrono::seconds::period>;
  331. auto now = std::chrono::high_resolution_clock::now();
  332. return FpSeconds(now.time_since_epoch()).count();
  333. }
  334. uint64_t Timer::GetTicksNanos()
  335. {
  336. if (useFakeSeconds)
  337. return (uint64_t) (FakeSeconds * NanosPerSecond);
  338. using Uint64Nanoseconds = std::chrono::duration<uint64_t, std::chrono::nanoseconds::period>;
  339. auto now = std::chrono::high_resolution_clock::now();
  340. return Uint64Nanoseconds(now.time_since_epoch()).count();
  341. }
  342. void Timer::initializeTimerSystem()
  343. {
  344. }
  345. void Timer::shutdownTimerSystem()
  346. {
  347. }
  348. #endif // OS-specific
  349. } // OVR