Skip to content

Instantly share code, notes, and snippets.

@noidexe
Last active February 26, 2025 18:21
Show Gist options
  • Save noidexe/0bf8861b2aee92ac21e91983154e1429 to your computer and use it in GitHub Desktop.
Save noidexe/0bf8861b2aee92ac21e91983154e1429 to your computer and use it in GitHub Desktop.
Cronometer.gd: A little class to time functions
## A little class to time functions.
## [br]
## Usage:
## [codeblock]
## var cronometer = Cronometer.new("Doing the thing..")
## #...
## cronometer.lap("Step 1 took: ")
## #...
## cronometer.lap("Step 2 took: ")
## cronometer.total("So far it took: ")
## #...
## cronometer.lap("Step 3 took: ")
## cronomater.total("Did the thing. Total time: ")
## [/codeblock]
extends RefCounted
class_name Cronometer
## Set during [method _init]. Holds the time when the cronometer was created
var _start_time : int
## Holds the time of the last time [method lap] was called
var _lap_time : int
## Creates a new Cronometer and optionally prints a message like "Starting..","Loading", etc.
func _init( message : String = "") -> void:
_start_time = Time.get_ticks_usec()
_lap_time = _start_time
if message:
print(message)
## Marks a lap and optionally prints a message with the lap time
func lap( message : String = ""):
var new_lap = Time.get_ticks_usec()
if message:
_print(new_lap - _lap_time, message)
_lap_time = new_lap
## Prints a message with the total time since the Cronometer was created
func total( message : String = "Total time: "):
_print(Time.get_ticks_usec() - _start_time, message)
## Returns the amount of µs since the cronometer was started
func get_elapsed() -> int:
return Time.get_ticks_usec() - _start_time
## Returns the amount of µs since the last lap
func get_elapsed_since_lap() -> int:
return Time.get_ticks_usec() - _lap_time
## Helper method to print a message and automatically convert the elapsed time to the most fitting SI prefix
func _print(elapsed: float, message : String):
var unit : String
if elapsed < 1000:
unit = "µs"
elif elapsed < 1000000:
elapsed /= 1000
unit = "ms"
else:
elapsed /= 1000000
unit = "s"
print(message + " [ %s%s ]" % [elapsed, unit])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment