OVR_Timer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. static 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::useVirtualSeconds = false;
  47. double Timer::VirtualSeconds = 0.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(useVirtualSeconds)
  57. return VirtualSeconds;
  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 (useVirtualSeconds)
  74. return (uint64_t) (VirtualSeconds * 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. // In Vista+ we are able to use QPC exclusively.
  142. bool UsingVistaOrLater;
  143. CRITICAL_SECTION TimeCS;
  144. // timeGetTime() support with wrap.
  145. uint32_t OldMMTimeMs;
  146. uint32_t MMTimeWrapCounter;
  147. // Cached performance frequency result.
  148. uint64_t PerfFrequency; // cycles per second, typically a large value like 3000000, but usually not the same as the CPU clock rate.
  149. double PerfFrequencyInverse; // seconds per cycle (will be a small fractional value).
  150. double PerfFrequencyInverseNanos; // nanoseconds per cycle.
  151. // Computed as (perfCounterNanos - ticksCounterNanos) initially,
  152. // and used to adjust timing.
  153. uint64_t PerfMinusTicksDeltaNanos;
  154. // Last returned value in nanoseconds, to ensure we don't back-step in time.
  155. uint64_t LastResultNanos;
  156. };
  157. static PerformanceTimer Win32_PerfTimer;
  158. void PerformanceTimer::Initialize()
  159. {
  160. ::InitializeCriticalSection(&TimeCS);
  161. MMTimeWrapCounter = 0;
  162. getFrequency();
  163. #if defined(OVR_OS_WIN32) // Desktop Windows only
  164. // Set Vista flag. On Vista, we can just use QPC() without all the extra work
  165. OSVERSIONINFOEXW ver;
  166. ZeroMemory(&ver, sizeof(OSVERSIONINFOEXW));
  167. ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
  168. ver.dwMajorVersion = 6; // Vista+
  169. DWORDLONG condMask = 0;
  170. VER_SET_CONDITION(condMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
  171. // VerifyVersionInfo returns true if the OS meets the conditions set above
  172. UsingVistaOrLater = ::VerifyVersionInfoW(&ver, VER_MAJORVERSION, condMask) != 0;
  173. #else
  174. UsingVistaOrLater = true;
  175. #endif
  176. if (!UsingVistaOrLater)
  177. {
  178. #if defined(OVR_OS_WIN32) // Desktop Windows only
  179. // The following has the effect of setting the NT timer resolution (NtSetTimerResolution) to 1 millisecond.
  180. MMRESULT mmr = timeBeginPeriod(1);
  181. OVR_ASSERT(TIMERR_NOERROR == mmr);
  182. OVR_UNUSED(mmr);
  183. #endif
  184. #if defined(OVR_BUILD_DEBUG) && defined(OVR_OS_WIN32)
  185. HMODULE hNtDll = ::LoadLibraryW(L"NtDll.dll");
  186. if (hNtDll)
  187. {
  188. pNtQueryTimerResolution = (NtQueryTimerResolutionType)::GetProcAddress(hNtDll, "NtQueryTimerResolution");
  189. //pNtSetTimerResolution = (NtSetTimerResolutionType)::GetProcAddress(hNtDll, "NtSetTimerResolution");
  190. if (pNtQueryTimerResolution)
  191. {
  192. ULONG MinimumResolution; // in 100-ns units
  193. ULONG MaximumResolution;
  194. ULONG ActualResolution;
  195. pNtQueryTimerResolution(&MinimumResolution, &MaximumResolution, &ActualResolution);
  196. OVR_DEBUG_LOG(("NtQueryTimerResolution = Min %ld us, Max %ld us, Current %ld us", MinimumResolution / 10, MaximumResolution / 10, ActualResolution / 10));
  197. }
  198. ::FreeLibrary(hNtDll);
  199. }
  200. #endif
  201. }
  202. }
  203. void PerformanceTimer::Shutdown()
  204. {
  205. ::DeleteCriticalSection(&TimeCS);
  206. if (!UsingVistaOrLater)
  207. {
  208. #if defined(OVR_OS_WIN32) // Desktop Windows only
  209. MMRESULT mmr = timeEndPeriod(1);
  210. OVR_ASSERT(TIMERR_NOERROR == mmr);
  211. OVR_UNUSED(mmr);
  212. #endif
  213. }
  214. }
  215. uint64_t PerformanceTimer::GetTimeSeconds()
  216. {
  217. if (UsingVistaOrLater)
  218. {
  219. LARGE_INTEGER li;
  220. ::QueryPerformanceCounter(&li);
  221. OVR_ASSERT(PerfFrequencyInverse != 0); // Initialize should have been called earlier.
  222. return (uint64_t)(li.QuadPart * PerfFrequencyInverse);
  223. }
  224. return (uint64_t)(GetTimeNanos() * .0000000001);
  225. }
  226. double PerformanceTimer::GetTimeSecondsDouble()
  227. {
  228. if (UsingVistaOrLater)
  229. {
  230. LARGE_INTEGER li;
  231. ::QueryPerformanceCounter(&li);
  232. OVR_ASSERT(PerfFrequencyInverse != 0);
  233. return (li.QuadPart * PerfFrequencyInverse);
  234. }
  235. return (GetTimeNanos() * .0000000001);
  236. }
  237. uint64_t PerformanceTimer::GetTimeNanos()
  238. {
  239. uint64_t resultNanos;
  240. LARGE_INTEGER li;
  241. OVR_ASSERT(PerfFrequencyInverseNanos != 0); // Initialize should have been called earlier.
  242. if (UsingVistaOrLater) // Includes non-desktop platforms
  243. {
  244. // Then we can use QPC() directly without all that extra work
  245. ::QueryPerformanceCounter(&li);
  246. resultNanos = (uint64_t)(li.QuadPart * PerfFrequencyInverseNanos);
  247. return resultNanos;
  248. }
  249. // Pre-Vista computers:
  250. // Note that the Oculus SDK does not run on PCs before Windows 7 SP1
  251. // so this code path should never be taken in practice. We keep it here
  252. // since this is a nice reusable timing library that can be useful for
  253. // other projects.
  254. // On Win32 QueryPerformanceFrequency is unreliable due to SMP and
  255. // performance levels, so use this logic to detect wrapping and track
  256. // high bits.
  257. ::EnterCriticalSection(&TimeCS);
  258. // Get raw value and perf counter "At the same time".
  259. ::QueryPerformanceCounter(&li);
  260. DWORD mmTimeMs = timeGetTime();
  261. if (OldMMTimeMs > mmTimeMs)
  262. MMTimeWrapCounter++;
  263. OldMMTimeMs = mmTimeMs;
  264. // Normalize to nanoseconds.
  265. uint64_t perfCounterNanos = (uint64_t)(li.QuadPart * PerfFrequencyInverseNanos);
  266. uint64_t mmCounterNanos = ((uint64_t(MMTimeWrapCounter) << 32) | mmTimeMs) * 1000000;
  267. if (PerfMinusTicksDeltaNanos == 0)
  268. PerfMinusTicksDeltaNanos = perfCounterNanos - mmCounterNanos;
  269. // Compute result before snapping.
  270. //
  271. // On first call, this evaluates to:
  272. // resultNanos = mmCounterNanos.
  273. // Next call, assuming no wrap:
  274. // resultNanos = prev_mmCounterNanos + (perfCounterNanos - prev_perfCounterNanos).
  275. // After wrap, this would be:
  276. // resultNanos = snapped(prev_mmCounterNanos +/- 1ms) + (perfCounterNanos - prev_perfCounterNanos).
  277. //
  278. resultNanos = perfCounterNanos - PerfMinusTicksDeltaNanos;
  279. // Snap the range so that resultNanos never moves further apart then its target resolution.
  280. // It's better to allow more slack on the high side as timeGetTime() may be updated at sporadically
  281. // larger then 1 ms intervals even when 1 ms resolution is requested.
  282. if (resultNanos > (mmCounterNanos + MMTimerResolutionNanos*2))
  283. {
  284. resultNanos = mmCounterNanos + MMTimerResolutionNanos*2;
  285. if (resultNanos < LastResultNanos)
  286. resultNanos = LastResultNanos;
  287. PerfMinusTicksDeltaNanos = perfCounterNanos - resultNanos;
  288. }
  289. else if (resultNanos < (mmCounterNanos - MMTimerResolutionNanos))
  290. {
  291. resultNanos = mmCounterNanos - MMTimerResolutionNanos;
  292. if (resultNanos < LastResultNanos)
  293. resultNanos = LastResultNanos;
  294. PerfMinusTicksDeltaNanos = perfCounterNanos - resultNanos;
  295. }
  296. LastResultNanos = resultNanos;
  297. ::LeaveCriticalSection(&TimeCS);
  298. return resultNanos;
  299. }
  300. //------------------------------------------------------------------------
  301. // *** Timer - Platform Independent functions
  302. // Returns global high-resolution application timer in seconds.
  303. double Timer::GetSeconds()
  304. {
  305. return Win32_PerfTimer.GetTimeSecondsDouble();
  306. }
  307. double Timer::GetVirtualSeconds()
  308. {
  309. if (useVirtualSeconds)
  310. return VirtualSeconds;
  311. return Win32_PerfTimer.GetTimeSecondsDouble();
  312. }
  313. // Delegate to PerformanceTimer.
  314. uint64_t Timer::GetVirtualTicksNanos()
  315. {
  316. if (useVirtualSeconds)
  317. return (uint64_t) (VirtualSeconds * NanosPerSecond);
  318. return Win32_PerfTimer.GetTimeNanos();
  319. }
  320. uint64_t Timer::GetTicksNanos()
  321. {
  322. return Win32_PerfTimer.GetTimeNanos();
  323. }
  324. // Windows version also provides the performance frequency inverse.
  325. double Timer::GetPerfFrequencyInverse()
  326. {
  327. return Win32_PerfTimer.GetFrequencyInverse();
  328. }
  329. void Timer::initializeTimerSystem()
  330. {
  331. Win32_PerfTimer.Initialize();
  332. }
  333. void Timer::shutdownTimerSystem()
  334. {
  335. Win32_PerfTimer.Shutdown();
  336. }
  337. #else // C++11 standard compliant platforms
  338. double Timer::GetSeconds()
  339. {
  340. if(useVirtualSeconds)
  341. return VirtualSeconds;
  342. using FpSeconds = std::chrono::duration<double, std::chrono::seconds::period>;
  343. auto now = std::chrono::high_resolution_clock::now();
  344. return FpSeconds(now.time_since_epoch()).count();
  345. }
  346. double Timer::GetVirtualSeconds()
  347. {
  348. if(useVirtualSeconds)
  349. return VirtualSeconds;
  350. using FpSeconds = std::chrono::duration<double, std::chrono::seconds::period>;
  351. auto now = std::chrono::high_resolution_clock::now();
  352. return FpSeconds(now.time_since_epoch()).count();
  353. }
  354. uint64_t Timer::GetTicksNanos()
  355. {
  356. if (useVirtualSeconds)
  357. return (uint64_t) (VirtualSeconds * NanosPerSecond);
  358. using Uint64Nanoseconds = std::chrono::duration<uint64_t, std::chrono::nanoseconds::period>;
  359. auto now = std::chrono::high_resolution_clock::now();
  360. return Uint64Nanoseconds(now.time_since_epoch()).count();
  361. }
  362. void Timer::initializeTimerSystem()
  363. {
  364. }
  365. void Timer::shutdownTimerSystem()
  366. {
  367. }
  368. #endif // OS-specific
  369. } // OVR