在PHP中测量脚本执行时间

在PHP中测量脚本执行时间

PHP:PHP(超文本预处理器)是一种广泛使用的开源服务器端脚本语言,专为 Web 开发而设计。它最初由 Rasmus Lerdorf 于 1994 年创建,现已发展成为全球数百万开发人员使用的强大语言。

PHP主要用于开发动态网页和Web应用程序。它允许开发人员在HTML中嵌入PHP代码,使得在展示层中混合服务器端逻辑变得容易。PHP脚本在服务器上执行,然后将生成的HTML发送到客户端浏览器。

在PHP中有几种方法可以测量脚本执行时间

以下是一些常用的方法:

  • 使用microtime()函数

  • 使用time()函数

  • 使用 hrtime() 函数(在 PHP 7.3 及更高版本中可用)

  • 结合使用 microtime(true) 函数和 memory_get_peak_usage() 函数来测量峰值内存使用情况

使用microtime()函数

下面是使用 PHP 中的 microtime() 函数测量脚本执行时间的示例:

// Start the timer $start = microtime(true); // Code to measure execution time // End the timer $end = microtime(true); // Calculate the execution time $executionTime = $end - $start; // Output the result echo "Script execution time: " . $executionTime . " seconds"; 登录后复制