มีด้วยกัน 2 วิธี คือ
วัดผ่าน console
เราจะใช้ console.time() และ console.timeEnd() ในการวัดค่า
console.time("myCode");
// Code to be timed goes here
for (let i = 0; i < 1000000; i++) {
// Some operation
}
console.timeEnd("myCode");วัดผ่าน Performance Now
ส่วนอีกวิธีก็จะเป็นการใช้คำสั่ง performance.now() นับตอนเริ่ม และ ตอนจบ แล้วเอาค่ามาลบกัน
const startTime = performance.now();
// Code to be timed
for (let i = 0; i < 1000000; i++) {
// Some operation
}
const endTime = performance.now();
const executionTime = endTime - startTime;
console.log(`Execution time: ${executionTime} milliseconds`);ทั้ง 2 วิธีนี้ให้วิธีการวัดเวลาการทำงานของบล็อกโค้ด console.time และ console.timeEnd เป็นวิธีการจับเวลาแบบง่าย ๆ ตรงไปตรงมา
ในขณะที่ performance. now() มีความแม่นยำสูงกว่า และ เหมาะสำหรับการวัดที่แม่นยำมากขึ้น เลือกวิธีที่เหมาะสมที่สุดกับระดับความแม่นยำที่ต้องการ