ที่นี่เราจะดูวิธีดึงเวลา (Elapsed Time ของโปรแกรมหรือเวลาอื่นๆ)
ที่นี่เราใช้ไลบรารี Linux สำหรับ C++ มีโครงสร้างชื่อ timeval โครงสร้างนี้เก็บเวลาในหน่วยวินาทีและมิลลิวินาที เราสามารถสร้าง timeval สองตัวสำหรับเริ่มต้นและสิ้นสุด แล้วหาความต่างจากพวกมัน
ตัวอย่าง
#include <sys/time.h> #include <iostream> #include <unistd.h> using namespace std; main() { struct timeval start_time, end_time; long milli_time, seconds, useconds; gettimeofday(&start_time, NULL); cout << "Enter something: "; char ch; cin >> ch; gettimeofday(&end_time, NULL); seconds = end_time.tv_sec - start_time.tv_sec; //วินาที useconds = end_time.tv_usec - start_time.tv_usec; //ไมโครวินาที milli_time = ((seconds) * 1000 + useconds/1000.0); cout << "Elapsed time: " << milli_time <<" milliseconds\n"; }
ผลลัพธ์
Enter something: h Elapsed time: 2476 milliseconds