PHP检测每一段代码执行时间

2025-3-26 / 0 评论 / 2 阅读

http://www.12xl.cn/index.php/post/191.html

在写PHP项目的时候,发现速度很慢,于是查看一下是哪里影响的。

  1. <?php
  2. // 实例1

  3. /**
  4. * @start time
  5. */
  6. function proStartTime() {
  7. global \$startTime;
  8. \$mtime1 = explode(" ", microtime());
  9. \$startTime = \$mtime1[1] + \$mtime1[0];
  10. }

  11. /**
  12. * @End time
  13. */
  14. function proEndTime() {
  15. global \$startTime,\$set;
  16. \$mtime2 = explode(" ", microtime());
  17. \$endtime = \$mtime2[1] + \$mtime2[0];
  18. \$totaltime = (\$endtime - \$startTime);
  19. \$totaltime = number_format(\$totaltime, 7);
  20. echo "process time: ".\$totaltime."\r\n";
  21. }

  22. // 程序调用开始记时
  23. proStartTime();

  24. sleep(1); // sleep() 延时代码执行若干秒
  25. proEndTime(); // 程序在每一段所消耗的执行时间
  26. sleep(2);
  27. proEndTime();
  28. sleep(3);
  29. proEndTime();


  30. /************************************************* 华丽的分割线 **************************************************/

  31. // 实例2

  32. \$t1 = microtime(true);
  33. sleep(3);
  34. \$t2 = microtime(true);
  35. echo '程序耗时'.round(\$t2-\$t1,3).'秒';

  36. ?>