Linux में C++ का उपयोग करके मिलीसेकंड प्रिसिजन में समय मापने के लिए gettimeofday() (POSIX) या C++11 <chrono> लाइब्रेरी का उपयोग करें।
विधि 1: gettimeofday() (POSIX, लेगेसी)
#include <sys/time.h>
#include <iostream>
#include <unistd.h>
using namespace std;
int main() {
struct timeval start, end;
long milliseconds, seconds, useconds;
gettimeofday(&start, NULL);
cout << "Press Enter to stop...";
cin.get();
gettimeofday(&end, NULL);
seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;
milliseconds = ((seconds) * 1000 + useconds / 1000.0);
cout << "Elapsed time: " << milliseconds << " milliseconds\n";
return 0;
}
विधि 2: C++11 chrono (आधुनिक, पोर्टेबल)
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
int main() {
auto start = high_resolution_clock::now();
cout << "Press Enter to stop...";
cin.get();
auto end = high_resolution_clock::now();
// विभिन्न यूनिट्स में
auto ns = duration_cast<nanoseconds>(end - start).count();
auto us = duration_cast<microseconds>(end - start).count();
auto ms = duration_cast<milliseconds>(end - start).count();
auto s = duration_cast<seconds>(end - start).count();
cout << "\nNanoseconds: " << ns;
cout << "\nMicroseconds: " << us;
cout << "\nMilliseconds: " << ms;
cout << "\nSeconds: " << s << endl;
// फ्लोटिंग पॉइंट प्रिसिजन
auto ms_fp = duration<double, milli>(end - start).count();
cout << "Milliseconds (float): " << ms_fp << endl;
return 0;
}
आउटपुट
Press Enter to stop... Elapsed time: 2476 milliseconds // chrono version: Nanoseconds: 2476123456 Microseconds: 2476123 Milliseconds: 2476 Seconds: 2 Milliseconds (float): 2476.123456
विधि 3: clock_gettime() (Linux-विशिष्ट, उच्च प्रिसिजन)
#include <iostream>
#include <time.h>
using namespace std;
int main() {
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
// ... काम करें ...
clock_gettime(CLOCK_MONOTONIC, &end);
long ms = (end.tv_sec - start.tv_sec) * 1000 +
(end.tv_nsec - start.tv_nsec) / 1000000;
cout << "Elapsed: " << ms << " ms\n";
return 0;
}
सिफारिश: आधुनिक C++ (C++11+) में <chrono> का उपयोग करें - यह पोर्टेबल, टाइप-सेफ, और हाई-प्रिसिजन है।