<time.h> से clock() फंक्शन का उपयोग करके CPU समय मापें।
विधि
clock_t start = clock();- प्रारंभ समय लें।- कोड निष्पादित करें।
clock_t end = clock();- अंत समय लें।double cpu_time = (double)(end - start) / CLOCKS_PER_SEC;- सेकंड्स में समय।
उदाहरण
#include <stdio.h>
#include <time.h>
void wait_for_enter() {
printf("Press Enter to stop...\n");
while (getchar() != '\n'); // एंटर की प्रतीक्षा
}
int main() {
clock_t start = clock();
printf("Timer started\n");
wait_for_enter();
clock_t end = clock();
double elapsed = (double)(end - start) / CLOCKS_PER_SEC;
printf("Timer stopped\n");
printf("Elapsed CPU time: %.3f seconds\n", elapsed);
return 0;
}
आउटपुट
Timer started Press Enter to stop... Timer stopped Elapsed CPU time: 5.218 seconds
महत्वपूर्ण बिंदु
clock()**CPU समय** मापता है, वॉल-क्लॉक समय नहीं। मल्टी-थ्रेडेड प्रोग्राम में यह थ्रेड्स के CPU समय का योग हो सकता है।CLOCKS_PER_SECआमतौर पर 1,000,000 (POSIX) या 1000 (विंडोज)।- उच्च परिशुद्धता वॉल-क्लॉक समय के लिए:
उच्च परिशुद्धता विकल्प (POSIX)
#include <time.h>
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
// ... कोड ...
clock_gettime(CLOCK_MONOTONIC, &end);
double elapsed = (end.tv_sec - start.tv_sec) +
(end.tv_nsec - start.tv_nsec) / 1e9;
C++11 लाइब्रेरी
#include <chrono> #include <iostream> auto start = std::chrono::high_resolution_clock::now(); // ... कोड ... auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); std::cout << duration.count() << " ms\n";