0
# Timer and Timing
1
2
High-precision timing functions for animations, frame rate control, and custom timer callbacks. PySDL2 provides comprehensive timing capabilities for time-sensitive applications like games and multimedia software.
3
4
## Capabilities
5
6
### Basic Time Queries
7
8
Functions for getting current time and implementing delays.
9
10
```python { .api }
11
def SDL_GetTicks() -> int:
12
"""
13
Get the number of milliseconds since SDL library initialization.
14
15
Returns:
16
Milliseconds since SDL_Init() was called
17
"""
18
19
def SDL_GetTicks64() -> int:
20
"""
21
Get the number of milliseconds since SDL library initialization as 64-bit value.
22
23
Returns:
24
Milliseconds since SDL_Init() as 64-bit integer (SDL 2.0.18+)
25
"""
26
27
def SDL_Delay(ms: int) -> None:
28
"""
29
Wait a specified number of milliseconds before returning.
30
31
Parameters:
32
- ms: milliseconds to delay
33
"""
34
```
35
36
### High-Precision Timing
37
38
High-resolution performance counter functions for precise timing measurements.
39
40
```python { .api }
41
def SDL_GetPerformanceCounter() -> int:
42
"""
43
Get the current value of the high resolution counter.
44
45
Returns:
46
Current counter value in platform-specific units
47
"""
48
49
def SDL_GetPerformanceFrequency() -> int:
50
"""
51
Get the count per second of the high resolution counter.
52
53
Returns:
54
Counter frequency in counts per second
55
"""
56
```
57
58
### Custom Timers
59
60
Timer callback system for creating custom periodic or one-shot timers.
61
62
```python { .api }
63
def SDL_AddTimer(interval: int, callback: SDL_TimerCallback, param: Any) -> int:
64
"""
65
Add a new timer to the pool of timers already running.
66
67
Parameters:
68
- interval: timer interval in milliseconds
69
- callback: function to call when timer expires
70
- param: parameter to pass to callback function
71
72
Returns:
73
Timer ID on success, 0 on error
74
"""
75
76
def SDL_RemoveTimer(timer_id: int) -> bool:
77
"""
78
Remove a timer knowing its ID.
79
80
Parameters:
81
- timer_id: ID of timer to remove
82
83
Returns:
84
True if timer was removed successfully
85
"""
86
```
87
88
### Utility Functions
89
90
```python { .api }
91
def SDL_TICKS_PASSED(A: int, B: int) -> bool:
92
"""
93
Compare SDL tick values for proper overflow handling.
94
95
Parameters:
96
- A: first tick value
97
- B: second tick value
98
99
Returns:
100
True if A has passed B, accounting for overflow
101
"""
102
```
103
104
## Usage Examples
105
106
### Basic Timing
107
108
```python
109
import sdl2
110
111
# Initialize SDL
112
sdl2.SDL_Init(sdl2.SDL_INIT_TIMER)
113
114
# Get current time
115
start_time = sdl2.SDL_GetTicks()
116
117
# Do some work...
118
sdl2.SDL_Delay(1000) # Wait 1 second
119
120
# Calculate elapsed time
121
elapsed = sdl2.SDL_GetTicks() - start_time
122
print(f"Elapsed time: {elapsed}ms")
123
```
124
125
### High-Precision Timing
126
127
```python
128
import sdl2
129
130
# Get high-resolution timer frequency
131
frequency = sdl2.SDL_GetPerformanceFrequency()
132
print(f"Timer frequency: {frequency} Hz")
133
134
# Measure precise timing
135
start_counter = sdl2.SDL_GetPerformanceCounter()
136
137
# Do time-critical work...
138
139
end_counter = sdl2.SDL_GetPerformanceCounter()
140
141
# Calculate elapsed time in seconds
142
elapsed_seconds = (end_counter - start_counter) / frequency
143
elapsed_ms = elapsed_seconds * 1000
144
print(f"Precise elapsed time: {elapsed_ms:.3f}ms")
145
```
146
147
### Frame Rate Control
148
149
```python
150
import sdl2
151
152
# Target 60 FPS
153
TARGET_FPS = 60
154
FRAME_TIME = 1000 // TARGET_FPS # ~16.67ms per frame
155
156
# Game loop with frame rate control
157
running = True
158
last_time = sdl2.SDL_GetTicks()
159
160
while running:
161
current_time = sdl2.SDL_GetTicks()
162
frame_time = current_time - last_time
163
164
if frame_time >= FRAME_TIME:
165
# Update game logic
166
update_game()
167
168
# Render frame
169
render_frame()
170
171
last_time = current_time
172
else:
173
# Sleep for remaining frame time
174
sleep_time = FRAME_TIME - frame_time
175
if sleep_time > 0:
176
sdl2.SDL_Delay(sleep_time)
177
```
178
179
### Custom Timer Callbacks
180
181
```python
182
import sdl2
183
from ctypes import c_void_p
184
185
def timer_callback(interval, param):
186
"""Timer callback function"""
187
print(f"Timer fired! Interval: {interval}ms")
188
return interval # Return interval to repeat, 0 to stop
189
190
# Initialize SDL
191
sdl2.SDL_Init(sdl2.SDL_INIT_TIMER)
192
193
# Add a timer that fires every 500ms
194
timer_id = sdl2.SDL_AddTimer(500, timer_callback, None)
195
196
if timer_id != 0:
197
print(f"Timer added with ID: {timer_id}")
198
199
# Let timer run for a while
200
sdl2.SDL_Delay(3000)
201
202
# Remove the timer
203
if sdl2.SDL_RemoveTimer(timer_id):
204
print("Timer removed successfully")
205
else:
206
print("Failed to add timer")
207
```
208
209
### Delta Time Calculation
210
211
```python
212
import sdl2
213
214
class GameTimer:
215
def __init__(self):
216
self.last_time = sdl2.SDL_GetPerformanceCounter()
217
self.frequency = sdl2.SDL_GetPerformanceFrequency()
218
219
def get_delta_time(self):
220
"""Get delta time in seconds since last call"""
221
current_time = sdl2.SDL_GetPerformanceCounter()
222
delta = (current_time - self.last_time) / self.frequency
223
self.last_time = current_time
224
return delta
225
226
# Usage in game loop
227
timer = GameTimer()
228
229
while running:
230
dt = timer.get_delta_time()
231
232
# Update game objects with delta time
233
player.update(dt)
234
enemies.update(dt)
235
236
# Render frame
237
render()
238
```
239
240
## Types
241
242
```python { .api }
243
# Timer callback function type
244
SDL_TimerCallback = Callable[[int, Any], int]
245
"""
246
Timer callback function signature.
247
248
Parameters:
249
- interval: timer interval in milliseconds
250
- param: user data passed to SDL_AddTimer
251
252
Returns:
253
- Next timer interval in milliseconds, or 0 to cancel timer
254
"""
255
256
SDL_TimerID = int
257
"""Timer identifier returned by SDL_AddTimer."""
258
```