Start and stop a timer PHP

Start and stop a timer PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Start and Stop a Timer in PHP

Measuring elapsed time for an external process launched via exec() requires a fundamental understanding of how PHP handles timing and how operating systems report process durations. The core mechanism relies on capturing the wall-clock time before initiating the command and again immediately after its termination. However, simply calling time() or using microtime(true) at two different points in your script is insufficient if you are measuring the duration of a long-running external executable. This is because PHP scripts often terminate long before the external process finishes, especially when dealing with .exe files that might run independently or for extended periods.

To accurately measure the time an external command takes to complete, you must prevent the PHP script from exiting until the child process has finished its work. The exec() function is non-blocking by default, meaning it returns immediately after spawning the process but does not wait for it to finish. If your goal is to capture the total execution time of the .exe file, you need to ensure the script pauses until that specific process exits.

You can achieve this by appending the 2>&1 flag or using a dedicated function wrapper around exec() that captures the exit status and output while blocking execution. A common approach involves using shell_exec() instead of exec(). Unlike exec(), which returns on completion without waiting for the subprocess to finish (depending on configuration), shell_exec() blocks until the command finishes and returns the entire standard output as a string. While shell_exec() is convenient, it can consume significant memory for large outputs. If you prefer sticking with exec(), you must explicitly call pcntl_waitpid() (on Windows) or wait via process control mechanisms depending on your server environment, though PHP's default behavior often requires careful handling to ensure the script doesn't exit prematurely.

Here is a practical pattern using shell_exec() combined with microtime(true) to calculate precise elapsed time in seconds:

$start = microtime(true);

$output = shell_exec('./my_application.exe');

$end = microtime(true);

$total_seconds = $end - $start;

echo "The application took {$total_seconds} seconds to complete.";
echo "\nOutput:\n" . $output;

In this example, shell_exec() ensures the PHP script remains active until my_application.exe finishes. The microtime(true) function returns a Unix timestamp with microsecond precision, allowing for sub-second accuracy. This is crucial because standard time() only provides integer seconds, which might introduce significant error if the process runs for less than one second or fluctuates slightly.

However, there are trade-offs to consider regarding resource usage and output handling. If your .exe generates a massive amount of data, capturing it all into memory via shell_exec() could lead to out-of-memory errors on constrained servers. In production environments where the command produces large logs or streams, you should redirect the output to a file first, then read that file afterward. This approach decouples the memory usage of the PHP script from the volume of data produced by the external program.

Another consideration is cross-platform compatibility. The shell_exec() function behaves differently on Windows versus Linux. On Windows, executing .exe files usually works seamlessly if the path is correct and the file extension is included. If you are running this logic in a containerized environment or a restricted CLI, ensure that execution permissions are granted to the script.

For high-performance requirements where sub-millisecond precision is critical, hrtime() functions available in PHP 8+ provide nanosecond resolution. While microtime(true) remains sufficient for most application-level timing tasks, understanding the underlying clock source helps when debugging performance regressions. Always verify that the system clock hasn't been adjusted or synchronized between the start and end measurements, as this could skew results significantly.

If you are building complex monitoring systems where timing data needs to be logged consistently regardless of server load, consider integrating these metrics into a broader logging strategy. Tools like Laravel Company offer robust logging utilities that can help structure these timing events within larger application architectures, ensuring that performance data is actionable and not just transient console output.

Our network