ExecutionTimer

Introduction

The ExecutionTimer class in JiFramework provides a simple yet powerful way to measure the execution time of code blocks and functions within your application. It is designed to help developers analyze and optimize the performance of their code by providing precise timing measurements.

Key Features:

  • Start and Stop Timing: Manually start and stop the timer to measure specific code blocks.
  • Elapsed Time Retrieval: Get the elapsed time in seconds, milliseconds, or microseconds.
  • Reset Functionality: Reset the timer to reuse it for multiple measurements.
  • Static Measure Method: Conveniently measure the execution time of any callable function or method.
  • Lightweight and Easy to Use: Minimal setup required; integrate into your code quickly.

Usage:

// Option 1: Initialize the ExecutionTimer through the App
use JIFramework\Core\App\App;
$app = new App();
$timer = $app->executionTimer;

OR 

// Option 2: Directly instantiate the ExecutionTimer
use JIFramework\Core\Utilities\Performance\ExecutionTimer;
$timer = new ExecutionTimer();

Explanation:

  • Option 1: Initializes the App class and retrieves the ExecutionTimer instance through it, using the framework's main entry point.
  • Option 2: Directly creates a ExecutionTimer instance.

start()

Method: start(): void

Description: Starts the execution timer by recording the current time.

Parameters: None

Returns: void

Usage:

$timer->start();

// Place the code you want to measure here
for ($i = 0; $i < 1000000; $i++) {
    // Some operation
}

Explanation:

  • Initializes the timer by setting the startTime to the current time in microseconds.
  • Resets endTime and elapsedTime to zero.
  • Call start() before the code block you want to measure.

stop()

Method: stop(): void

Description: Stops the execution timer and calculates the elapsed time since start() was called.

Parameters: None

Returns: void

Usage:

$timer->stop();

Explanation:

  • Sets the endTime to the current time in microseconds.
  • Calculates elapsedTime by subtracting startTime from endTime.
  • Call stop() after the code block you want to measure.

getElapsedTime()

Method: getElapsedTime(): float

Description: Retrieves the elapsed time in seconds.

Parameters: None

Returns: A float representing the elapsed time in seconds.

Usage:

$elapsedTime = $timer->getElapsedTime();
echo "Elapsed Time: " . $elapsedTime . " seconds";

/*
Sample $elapsedTime:

Elapsed Time: 0.123456 seconds
*/

Explanation:

  • If the timer has not been stopped, it calculates the elapsed time up to the current moment.
  • Returns the elapsedTime value, which is the difference between endTime and startTime.

getElapsedTimeInMilliseconds()

Method: getElapsedTimeInMilliseconds(): float

Description: Retrieves the elapsed time in milliseconds.

Parameters: None

Returns: A float representing the elapsed time in milliseconds.

Usage:

$elapsedTimeMs = $timer->getElapsedTimeInMilliseconds();
echo "Elapsed Time: " . $elapsedTimeMs . " milliseconds";

/*
Sample $elapsedTimeMs:

Elapsed Time: 123.456 milliseconds
*/

Explanation:

  • Calls getElapsedTime() and multiplies the result by 1000 to convert seconds to milliseconds.

getElapsedTimeInMicroseconds()

Method: getElapsedTimeInMicroseconds(): float

Description: Retrieves the elapsed time in microseconds.

Parameters: None

Returns: A float representing the elapsed time in microseconds.

Usage:

$elapsedTimeUs = $timer->getElapsedTimeInMicroseconds();
echo "Elapsed Time: " . $elapsedTimeUs . " microseconds";

/*
Sample $elapsedTimeUs:

Elapsed Time: 123456.789 microseconds
*/

Explanation:

  • Calls getElapsedTime() and multiplies the result by 1,000,000 to convert seconds to microseconds.

reset()

Method: reset(): void

Description: Resets the timer by clearing the start time, end time, and elapsed time.

Parameters: None

Returns: void

Usage:

$timer->reset();

Explanation:

  • Sets startTime, endTime, and elapsedTime to zero.
  • Allows the timer to be reused for measuring another code block.

measure()

Method: measure(callable $callback, ...$args): array

Description: Static method that measures the execution time of a callable function or method.

Parameters:

  • $callback (callable): The function or method to execute.
  • ...$args: Variable number of arguments to pass to the callback.

Returns: An array containing:

  • 'result': The result returned by the callback function.
  • 'elapsed_time': The execution time in seconds as a float.

Usage:

$result = ExecutionTimer::measure(function($n) {
    $sum = 0;
    for ($i = 0; $i < $n; $i++) {
        $sum += $i;
    }
    return $sum;
}, 1000000);

/*
Sample $result:

array(2) {
  ["result"]=> int(499999500000)
  ["elapsed_time"]=> float(0.123456)
}
*/

echo "Result: " . $result['result'] . "\n";
echo "Elapsed Time: " . $result['elapsed_time'] . " seconds";

Explanation:

  • Creates a new ExecutionTimer instance internally.
  • Starts the timer, executes the callback with the provided arguments, and stops the timer.
  • Returns an array with the callback's result and the elapsed time.
  • Useful for quickly measuring functions without manual start/stop calls.

Usage Examples

Example 1: Measuring Execution Time of a Code Block

$timer->start();

// Code block to measure
for ($i = 0; $i < 1000000; $i++) {
    // Some operation
}

// Stop the timer
$timer->stop();

// Get elapsed time
$elapsedTime = $timer->getElapsedTime();
$elapsedTimeMs = $timer->getElapsedTimeInMilliseconds();

echo "Elapsed Time: " . $elapsedTime . " seconds\n";
echo "Elapsed Time: " . $elapsedTimeMs . " milliseconds\n";

/*
Sample output:

Elapsed Time: 0.089765 seconds
Elapsed Time: 89.765 milliseconds
*/

Example 2: Measuring Execution Time of a Function Using measure()

// Function to measure
function calculateFactorial($n) {
    if ($n <= 1) return 1;
    return $n * calculateFactorial($n - 1);
}

// Use the static measure method
$result = ExecutionTimer::measure('calculateFactorial', 10);

/*
Sample $result:

array(2) {
  ["result"]=> int(3628800)
  ["elapsed_time"]=> float(0.000123)
}
*/

echo "Factorial Result: " . $result['result'] . "\n";
echo "Elapsed Time: " . ($result['elapsed_time'] * 1000) . " milliseconds\n";

/*
Sample output:

Factorial Result: 3628800
Elapsed Time: 0.123 milliseconds
*/

Example 3: Reusing the Timer for Multiple Measurements

// First measurement
$timer->start();
// Code block 1
sleep(1); // Simulate a 1-second task
$timer->stop();
echo "Task 1 Time: " . $timer->getElapsedTime() . " seconds\n";

/*
Sample output:

Task 1 Time: 1.001234 seconds
*/

// Reset the timer
$timer->reset();

// Second measurement
$timer->start();
// Code block 2
sleep(2); // Simulate a 2-second task
$timer->stop();
echo "Task 2 Time: " . $timer->getElapsedTime() . " seconds\n";

/*
Sample output:

Task 2 Time: 2.002345 seconds
*/