Stopwatch
The Stopwatch library provides a simple way to measure elapsed time in Lua. It's useful for benchmarking code or measuring the duration of operations.
Creating a Stopwatch
Stopwatch.new()
Creates a new Stopwatch object.
Stopwatch Methods
stopwatch:Start()
Starts the stopwatch. If the stopwatch is already running, this method has no effect.
stopwatch:Stop()
Stops the stopwatch. If the stopwatch is not running, this method has no effect.
stopwatch:Reset()
Resets the stopwatch to zero and stops it if it's running.
stopwatch:ElapsedTime()
Returns the total elapsed time in seconds. If the stopwatch is running, it returns the time since it was started. If it's stopped, it returns the time between the start and stop.
Examples
Basic Usage
local sw = Stopwatch.new()
sw:Start()
-- Do some work here
sw:Stop()
print("Operation took", sw:ElapsedTime(), "seconds")
Measuring Multiple Intervals
local sw = Stopwatch.new()
sw:Start()
-- First operation
local time1 = sw:ElapsedTime()
-- Second operation
local time2 = sw:ElapsedTime()
sw:Stop()
print("First operation:", time1, "seconds")
print("Second operation:", time2 - time1, "seconds")
print("Total time:", sw:ElapsedTime(), "seconds")
Resetting and Reusing
local sw = Stopwatch.new()
sw:Start()
-- Do some work
sw:Stop()
print("First operation:", sw:ElapsedTime(), "seconds")
sw:Reset()
sw:Start()
-- Do some other work
sw:Stop()
print("Second operation:", sw:ElapsedTime(), "seconds")