Elapsed Time คือเวลาที่ผ่านไประหว่างจุดเริ่มต้นและจุดสิ้นสุด Java มีหลายวิธีในการวัด
1. ใช้ System.currentTimeMillis()
คืนค่าเวลาปัจจุบันเป็นมิลลิวินาที ง่ายที่สุด แต่ความแม่นยำจำกัด
public class Example {
public void test() {
int num = 0;
for (int i = 0; i <= 50; i++) {
num = num + i;
System.out.print(num + ", ");
}
}
public static void main(String args[]) {
long begin = System.currentTimeMillis();
new Example().test();
long end = System.currentTimeMillis();
long time = end - begin;
System.out.println();
System.out.println("Elapsed Time: " + time + " milli seconds");
}
}
Elapsed Time: 4 milli seconds
2. ใช้ System.nanoTime()
คืนค่าเวลาปัจจุบันเป็นนาโนวินาที แม่นยำกว่า สำหรับวัดระยะเวลาสั้น
public class Example {
public static void main(String args[]) {
long begin = System.nanoTime();
new Example().test();
long end = System.nanoTime();
long time = end - begin;
System.out.println();
System.out.println("Elapsed Time: " + time + " nanoseconds");
}
}
Elapsed Time: 1530200 nanoseconds
3. ใช้ java.time.Instant และ Duration (Java 8+) - แนะนำ
ใช้ Time API สมัยใหม่ อ่านง่าย รองรับ Time Zone
import java.time.Duration;
import java.time.Instant;
public class Example {
public static void main(String args[]) {
Instant start = Instant.now();
new Example().test();
Instant end = Instant.now();
long time = Duration.between(start, end).toMillis();
System.out.println();
System.out.println(time + " Milli seconds");
}
}
3 Milli seconds
4. ใช้ Apache Commons StopWatch
ไลบรารีเสริมที่สะดวก มีฟีเจอร์ start, stop, reset, split
Maven Dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
ตัวอย่างโค้ด
import org.apache.commons.lang3.time.StopWatch;
public class Example {
public static void main(String args[]) {
StopWatch obj = new StopWatch();
obj.start();
new Example().test();
obj.stop();
System.out.println();
System.out.println("Elapsed Time: " + obj.getTime() + " milli seconds");
}
}
Elapsed Time: 1 milli seconds
ตารางสรุปและคำแนะนำ
| วิธี | หน่วย | Java Version | ใช้เมื่อไหร่ |
|---|---|---|---|
| currentTimeMillis() | ms | 1.0+ | วัดเวลายาว ง่าย ไม่ต้องการความแม่นยำสูง |
| nanoTime() | ns | 1.5+ | Benchmarking, Profiling, วัดเวลาสั้น |
| Instant + Duration | ms/ns | 8+ | โปรเจกต์ใหม่ทุกโปรเจกต์ API ทันสมัย |
| StopWatch | ms | 1.5+ | ต้องการฟีเจอร์ split, reset, suspend |
ข้อผิดพลาดที่พบบ่อย
- ใช้ currentTimeMillis() วัดเวลาสั้นมาก (ต่ำกว่า 1ms) - จะได้ค่า 0 เสมอ
- ไม่ทำ Warm-up ก่อนวัด - ผลลัพธ์ครั้งแรกมักช้ากว่า
- ใช้ Date/Calendar ใหม่ - Legacy API มีปัญหา thread-safety
- คิดว่า nanoTime() คือเวลาจริง - มันเป็น relative time เท่านั้น