Blender V5.3
time.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "BLI_time.hh"
10
11#include <chrono>
12
13#ifdef WIN32
14
15# include <cmath>
16# include <cstdio>
17# include <windows.h>
18/* timeapi.h needs to be included after windows.h. */
19# include <timeapi.h>
20
21#else
22
23# include <thread>
24# include <unistd.h>
25
26#endif
27
28namespace blender {
29
31{
32 return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch())
33 .count();
34}
35
37{
38 return std::chrono::duration_cast<std::chrono::seconds>(
39 std::chrono::steady_clock::now().time_since_epoch())
40 .count();
41}
42
43#ifdef WIN32
44
45void BLI_time_sleep_ms(int ms)
46{
47 Sleep(ms);
48}
49
51{
52 /* Prefer thread-safety over caching the timer with a static variable. According to
53 * https://github.com/rust-lang/rust/pull/116461/files, this costs only approximately 2000ns. */
54 HANDLE timerHandle = CreateWaitableTimerExW(
55 nullptr, nullptr, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS);
56 if (!timerHandle) {
57 if (GetLastError() == ERROR_INVALID_PARAMETER) {
58 /* CREATE_WAITABLE_TIMER_HIGH_RESOLUTION is only supported since Windows 10, version 1803. */
59 DWORD duration_ms = DWORD(std::ceil(double(us) / 1000.0));
60 Sleep(duration_ms);
61 }
62 else {
63 fprintf(stderr,
64 "BLI_time_sleep_precise_us: CreateWaitableTimerExW failed: %lx\n",
65 GetLastError());
66 }
67 return;
68 }
69
70 /* Wait time is specified in 100 nanosecond intervals. */
71 LARGE_INTEGER wait_time;
72 wait_time.QuadPart = -us * 10;
73 if (!SetWaitableTimer(timerHandle, &wait_time, 0, nullptr, nullptr, 0)) {
74 fprintf(stderr, "BLI_time_sleep_precise_us: SetWaitableTimer failed: %lx\n", GetLastError());
75 CloseHandle(timerHandle);
76 return;
77 }
78
79 if (WaitForSingleObject(timerHandle, INFINITE) != WAIT_OBJECT_0) {
80 fprintf(
81 stderr, "BLI_time_sleep_precise_us: WaitForSingleObject failed: %lx\n", GetLastError());
82 CloseHandle(timerHandle);
83 return;
84 }
85
86 CloseHandle(timerHandle);
87}
88
89#else
90
92{
93 if (ms >= 1000) {
94 sleep(ms / 1000);
95 ms = (ms % 1000);
96 }
97
98 usleep(ms * 1000);
99}
100
102{
103 std::this_thread::sleep_for(std::chrono::microseconds(us));
104}
105
106#endif
107
108} // namespace blender
Platform independent time functions.
BMesh Iterators.
__int64 int64_t
Definition BKE_text.h:90
int64_t BLI_time_now_seconds_i()
Definition time.cc:36
void BLI_time_sleep_ms(int ms)
Definition time.cc:91
void BLI_time_sleep_precise_us(int us)
Definition time.cc:101
double BLI_time_now_seconds()
Definition time.cc:30