Trong bài viết này, chúng ta sẽ thảo luận về hàm difftime () trong C ++, cú pháp, cách làm việc và các giá trị trả về của nó.
Hàm difftime () là một hàm có sẵn trong C ++, được định nghĩa trong tệp tiêu đề. Hàm chấp nhận hai tham số kiểu time_t, hàm tính toán sự khác biệt giữa hai thời điểm
Cú pháp
double difftime(time_t end, time_t beginning);
Giá trị trả về
Trả về chênh lệch thời gian tính bằng giây, được lưu trữ dưới dạng dữ liệu kép.
Ví dụ
#include <stdio.h>
#include <time.h>
int main () {
time_t now;
struct tm newyear;
double seconds;
time(&now); /* get current time; */
newyear = *localtime(&now);
newyear.tm_hour = 0; newyear.tm_min = 0; newyear.tm_sec = 0;
newyear.tm_mon = 0; newyear.tm_mday = 1;
seconds = difftime(now,mktime(&newyear));
printf ("%.f seconds since new year in the current timezone.\n", seconds);
return 0;
} Đầu ra
Nếu chúng ta chạy đoạn mã trên, nó sẽ tạo ra kết quả sau -
3351041 seconds since new year in the current timezone.
Ví dụ
#include <iostream>
#include <ctime>
using namespace std;
int main() {
time_t start, ending;
long addition;
time(&start);
for (int i = 0;
i < 50000; i++) {
for (int j = 0; j < 50000; j++);
}
for (int i = 0; i < 50000; i++) {
for (int j = 0; j < 50000; j++);
} for (int i = 0; i < 50000; i++) {
for (int j = 0; j < 50000; j++);
} time(&ending);
cout << "Total time required = " << difftime(ending, start) << " seconds " << endl;
return 0;
} Đầu ra
Nếu chúng ta chạy đoạn mã trên, nó sẽ tạo ra kết quả sau -
Total time required = 37 seconds