Ark
Loading...
Searching...
No Matches
rate.Rate Class Reference

A convenience class for sleeping in a loop at a specified rate using perf_counter_ns for high precision. More...

Public Member Functions

None __init__ (self, float hz, bool reset=False)
 Initializes the Rate object with a specified rate in Hertz (Hz) and an optional reset flag.
float remaining (self)
 Returns the time remaining (in seconds) before the next sleep interval.
None sleep (self)
 Attempts to sleep at the specified rate.

Public Attributes

int last_time_ns = time.perf_counter_ns()
int sleep_dur_ns

Protected Member Functions

int _remaining (self, int curr_time_ns)
 Calculates the remaining time (in nanoseconds) before the next sleep interval.

Protected Attributes

bool _reset = reset

Detailed Description

A convenience class for sleeping in a loop at a specified rate using perf_counter_ns for high precision.

This class calculates the required sleep duration between loop iterations based on a specified rate (in Hz), and attempts to maintain that rate by sleeping for the appropriate amount of time. The rate is measured using nanoseconds for high precision.

Constructor & Destructor Documentation

◆ __init__()

None rate.Rate.__init__ ( self,
float hz,
bool reset = False )

Initializes the Rate object with a specified rate in Hertz (Hz) and an optional reset flag.

Parameters
hzThe target rate in Hertz (loops per second) to determine the sleep duration.
resetIf True, resets the timer if the system time moves backward. Defaults to False.

Member Function Documentation

◆ _remaining()

int rate.Rate._remaining ( self,
int curr_time_ns )
protected

Calculates the remaining time (in nanoseconds) before the next sleep interval.

Parameters
curr_time_nsThe current time in nanoseconds.
Returns
: The remaining time to sleep in nanoseconds. @raises RuntimeError: If time moved backward and reset is False.

◆ remaining()

float rate.Rate.remaining ( self)

Returns the time remaining (in seconds) before the next sleep interval.

Returns
: The remaining sleep time in seconds.

◆ sleep()

None rate.Rate.sleep ( self)

Attempts to sleep at the specified rate.

This method calculates the remaining time for the current cycle and sleeps for that duration to maintain the target rate. If the system time moved backward, a warning is printed. If the reset flag is set to False, a RuntimeError is raised.

@raises RuntimeError: If the system time moved backward and reset is False.

Member Data Documentation

◆ _reset

bool rate.Rate._reset = reset
protected

◆ last_time_ns

int rate.Rate.last_time_ns = time.perf_counter_ns()

◆ sleep_dur_ns

int rate.Rate.sleep_dur_ns
Initial value:
= int(
1e9 / hz
)

The documentation for this class was generated from the following file: