ฟังก์ชัน clock() ใน Header <ctime> (หรือ <time.h>) ใช้วัด Processor Time (CPU Time) ที่โปรแกรมใช้ไป ไม่ใช่ Wall-clock Time (Real Time) เหมาะสำหรับ Benchmarking และ Profiling
หลักการทำงาน
- คืนค่า
clock_t(Integer Type) = จำนวน Clock Ticks จากเริ่มโปรแกรม - ค่าคงที่
CLOCKS_PER_SEC= จำนวน Ticks ต่อวินาที (มักเป็น 1,000,000 บน Linux, 1000 บน Windows) - สูตร:
Elapsed Seconds = (end - start) / CLOCKS_PER_SEC
ตัวอย่างพื้นฐาน: วัดเวลาฟังก์ชัน
#include <iostream>
#include <ctime>
#include <thread>
#include <chrono>
void busy_work(int n) {
volatile long long sum = 0;
for (int i = 0; i < n; ++i) sum += i;
}
int main() {
clock_t start = clock();
busy_work(100'000'000);
clock_t end = clock();
double cpu_time = static_cast<double>(end - start) / CLOCKS_PER_SEC;
std::cout << "CPU Time: " << cpu_time << " seconds\n";
}
ตัวอย่างโต้ตอบ: หยุดด้วย Enter
#include <iostream>
#include <ctime>
void wait_for_enter() {
std::cout << "Press Enter to stop...\n";
std::cin.ignore(); // รอ Enter
}
int main() {
clock_t t = clock();
std::cout << "Timer starts\n";
wait_for_enter();
std::cout << "Timer ends\n";
t = clock() - t;
double time_taken = static_cast<double>(t) / CLOCKS_PER_SEC;
std::cout << "Program took " << time_taken << " seconds (CPU time)\n";
}
⚠️ ข้อจำกัดสำคัญของ clock()
| ปัญหา | รายละเอียด |
|---|---|
| CPU Time ≠ Wall Time | Multi-thread: CPU Time = Sum ของทุก Thread (อาจ > Real Time) |
| Resolution ต่ำ | Windows: ~1ms (CLOCKS_PER_SEC=1000), Linux: ~1μs (1,000,000) |
| Wrap Around | clock_t อาจ Overflow (32-bit: ~2147 วินาที ~36 นาที) |
| ไม่รวม Sleep/IO Wait | เฉพาะเวลาที่ CPU ทำงานจริง |
ทางเลือกทันสมัย: <chrono> (C++11) - แนะนำ
#include <chrono>
#include <iostream>
int main() {
// High Resolution Wall Clock
auto start = std::chrono::high_resolution_clock::now();
// ... work ...
std::this_thread::sleep_for(std::chrono::seconds(1)); // Sleep นับใน Wall Time
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Wall Time: " << duration.count() << " ms\n";
// CPU Time (C++11 ไม่มี Standard CPU Clock, ใช้ clock() หรือ OS API)
}
เมื่อไหร่ใช้ clock() vs chrono?
- clock(): Legacy Code, CPU Time Profiling (Algorithm Complexity Analysis), Simple Benchmark
- chrono::high_resolution_clock: Wall Time, Real-world Latency, I/O Bound, Modern Code
- chrono::steady_clock: Monotonic Clock (ไม่กระโดดเวลา) - ใช้ Interval Timing
สรุป
clock() วัด CPU Time แบบเก่า Resolution ต่ำ มีข้อจำกัด ใช้ <chrono> สำหรับ Modern C++ (Wall Time, High Resolution, Type Safety) หากต้องการ CPU Time อย่างแม่นยำใน Modern C++ อาจต้องใช้ Platform-Specific APIs (getrusage, GetProcessTimes)