Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP คำนวณ Execution Time ของ Script

ตัวอย่างโค้ด

<?php
$start = microtime(true);

$val = 1;
for ($i = 1; $i <= 1500; $i++) {
    $val++;
}

$end = microtime(true);
$exec_time = $end - $start;
echo "The execution time of the PHP script is: $exec_time sec";
?>

ผลลัพธ์

The execution time of the PHP script is: 0.000123 sec

คำอธิบาย

  • microtime(true) คืนค่า Unix Timestamp แบบ Float (Microseconds)
  • วัดเวลาเริ่มต้นก่อน Code Block และเวลาสิ้นสุดหลัง Code Block
  • ผลต่าง = Execution Time (Seconds)

Alternative: hrtime() (PHP 7.3+)

<?php
$start = hrtime(true);
// ... code ...
$end = hrtime(true);
$exec_ns = $end - $start;  // Nanoseconds
echo "Execution time: " . ($exec_ns / 1_000_000) . " ms";
?>

Built-in: $_SERVER['REQUEST_TIME_FLOAT']

สำหรับ Script Execution Time ทั้งหมด (ตั้งแต่ Request เริ่ม):

<?php
// ที่ท้าย Script
$total_time = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
echo "Total script time: $total_time sec";
?>

Profiling Tools

  • Xdebug + Webgrind/KCacheGrind - Detailed Profiling
  • Blackfire.io - Production Profiling
  • Tideways - APM/Profiling

Best Practice

  • วัดเฉพาะ Critical Sections (ไม่ใช่ทั้ง Script)
  • Run Multiple Iterations และเฉลี่ย (ลด Noise)
  • ใช้ Profiling Tools สำหรับ Production Analysis