C語言中計算函數(shù)執(zhí)行時間的三種方式
這篇文章主要介紹三種計算執(zhí)行時間的方式。
方式1: time + difftime
使用time.h標準庫中的time和difftime函數(shù)可以返回記錄的兩次time_t結(jié)構(gòu)的時間之間的差值,這種方式只能精確到秒級,代碼示例如下:
#include <stdio.h>
#include <time.h>
int fibonacci(int n) {
if(n == 0 || n == 1) return 1;
return fibonacci(n-1) + fibonacci(n-2);
}
int main() {
int n = 0;
while(~scanf("%d",&n)) {
time_t start_time=0, end_time=0;
time(&start_time);
printf("fibonacci(%d)=%d\n",n,fibonacci(n));
time(&end_time);
printf("Time Used: %f\n",difftime(end_time,start_time));
}
return 0;
}
- 執(zhí)行結(jié)果如下
45
fibonacci(45)=1836311903
Time Used: 9.000000
方式2: clock + CLOCKS_PER_SEC
另外利用clock函數(shù)代替time函數(shù)也能起到相同作用,這種方式通過計算兩個clock函數(shù)之間的時鐘單元來實現(xiàn),代碼示例如下:
#include <stdio.h>
#include <time.h>
int fibonacci(int n) {
if(n == 0 || n == 1) return 1;
return fibonacci(n-1) + fibonacci(n-2);
}
int main() {
int n = 0;
while(~scanf("%d",&n)) {
time_t start_time=0, end_time=0;
start_time=clock();
printf("fibonacci(%d)=%d\n",n,fibonacci(n));
end_time=clock();
printf("Time Used: %f\n",(double)(end_time-start_time)/CLOCKS_PER_SEC);
}
return 0;
}
- 執(zhí)行結(jié)果如下
45
fibonacci(45)=1836311903
Time Used: 8.715660
方式3: timeb+ftime
另外利用clock函數(shù)代替time函數(shù)也能起到相同作用,這種方式通過計算兩個clock函數(shù)之間的時鐘單元來實現(xiàn),代碼示例如下:
#include <stdio.h>
#include <sys/timeb.h>
#include <string.h>
int fibonacci(int n) {
if(n == 0 || n == 1) return 1;
return fibonacci(n-1) + fibonacci(n-2);
}
int main() {
int n = 0;
while(~scanf("%d",&n)) {
struct timeb start_time, end_time;
memset(&start_time,0,sizeof(struct timeb));
memset(&start_time,0,sizeof(struct timeb));
ftime(&start_time);
printf("fibonacci(%d)=%d\n",n,fibonacci(n));
ftime(&end_time);
printf("Time Used: %d.%d\n",end_time.time-start_time.time,end_time.millitm-start_time.millitm);
}
return 0;
}
- 執(zhí)行結(jié)果如下
45
fibonacci(45)=1836311903
Time Used: 8.621
總結(jié)
到此這篇關(guān)于C語言中計算函數(shù)執(zhí)行時間的三種方式的文章就介紹到這了,更多相關(guān)C語言計算函數(shù)執(zhí)行時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- C語言實現(xiàn)日期和時間處理的常用函數(shù)總結(jié)
- C語言數(shù)據(jù)結(jié)構(gòu)的時間復(fù)雜度和空間復(fù)雜度
- C語言實現(xiàn)時間處理工具的示例代碼
- C語言算法的時間復(fù)雜度和空間復(fù)雜度
- C語言系統(tǒng)日期和時間實例詳解
- C語言標準時間與秒單位相互轉(zhuǎn)換
- C語言數(shù)據(jù)結(jié)構(gòu)通關(guān)時間復(fù)雜度和空間復(fù)雜度
- C語言 詳細解析時間復(fù)雜度與空間復(fù)雜度
- C語言?超詳細講解算法的時間復(fù)雜度和空間復(fù)雜度
- C語言時間函數(shù)的ctime()和gmtime()你了解嗎
- C語言時間函數(shù)之mktime和difftime詳解
相關(guān)文章
CMake語法及CMakeList.txt簡單使用小結(jié)
Cmake主要用于開發(fā)跨平臺的C++項目,本文主要介紹了CMake語法及CMakeList.txt簡單使用小結(jié),具有一定的參考價值,感興趣的可以了解一下2022-05-05
基于Matlab實現(xiàn)BP神經(jīng)網(wǎng)絡(luò)交通標志識別
道路交通標志用以禁止、警告、指示和限制道路使用者有秩序地使用道路,?保障出行安全.若能自動識別道路交通標志,?則將極大減少道路交通事故的發(fā)生。本文將介紹基于Matlab實現(xiàn)BP神經(jīng)網(wǎng)絡(luò)交通標志識別,感興趣的可以學習一下2022-01-01
Visual Studio 2019配置qt開發(fā)環(huán)境的搭建過程
這篇文章主要介紹了Visual Studio 2019配置qt開發(fā)環(huán)境的搭建過程,本文圖文并茂給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03

