Last active
January 6, 2025 13:03
-
-
Save vijinho/87a0e27244333ce49386706f6a73b8e0 to your computer and use it in GitHub Desktop.
PHP Function Timer with results caching, memoization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Implement a memoization function to cache results of expensive function calls. | |
$timer = function ($function) { | |
// Create an array to store cached results based on function arguments. | |
$cache = []; | |
// Return a closure that wraps the original function. | |
return function (...$args) use ($function, &$cache) { | |
// Generate a unique key for the cache based on function arguments. | |
$key = serialize($args); | |
// Check if the result is already cached. | |
if (isset($cache[$key])) { | |
return $cache[$key]; | |
} | |
// Measure the start time of the function execution. | |
$start = microtime(true); | |
// Call the original function with the provided arguments and store the result. | |
$result = call_user_func_array($function, $args); | |
// Calculate the duration of the function execution and print it. | |
printf("Time taken: %f seconds\n", microtime(true) - $start); | |
// Cache the result for future calls with the same arguments. | |
$cache[$key] = $result; | |
return $result; | |
}; | |
}; | |
// Example usage: | |
function exampleFunction($x, $y) { | |
sleep(1); // Simulate an expensive operation | |
return $x + $y; | |
} | |
$timedExampleFunction = $timer('exampleFunction'); | |
echo $timedExampleFunction(5, 3) . "\n"; // Outputs the result and time taken for first call | |
echo $timedExampleFunction(5, 3) . "\n"; // Outputs only the cached result without additional time |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment