C\C++中計時、延時函式
阿新 • • 發佈:2019-01-26
C\C++標準庫中提供了兩種計時函式clock()和time()。其用法如下:
(1)clock()函式用法
void timeConsume()
{
double start,stop,durationTime;
start = clock();
/*
...程式碼片段
*/
stop = clock();
durationTime = ((double)(stop-start))/CLK_TCK;
cout << "程式耗時:" << durationTime << " s" << endl;
}
clock()函式返回值型別為clock_t.該函式計算結果是以內部處理器時間為計量單位的,所以必須把它除以時鐘頻率,從而得到以秒為單位的時間。這種方法在機器上測量的很精確。在這裡Windows和Linux環境下會有所區別.
Linux環境下,處理器內部時間頻率為:CLOCKS_PER_SEC.
(2)time()函式用法
void timeConsume()
{
double start,stop,durationTime;
start = time(NULL);
/*
...程式碼片段
*/
stop = time(NULL);
durationTime = (double)difftime(stop , start);
cout << "程式耗時:" << durationTime << " s" << endl;
}
time()函式返回值型別為time_t,所以也需要在輸出前將其轉換為double型別。與clock不同的是time()函式有一個引數,用來說明存放時間資訊的位置。由於並不想儲存這個時間,所以將引數設定為NULL。但是這種計時方法不如clock()函式精確,但是它不需要有關時鐘頻率的資訊。
(3)延時函式
在標準庫中可以使用Sleep()函式進行延時,其單位是毫秒,如果想要延遲5秒則其方法如下:
Sleep(5 *1000);
在MFC中也可以使用_sleep()函式進行實現延時功能。在Windows環境下,Sleep()函式首字母大寫,而在Linux系統下sleep()函式首字母要小寫。在Linux系統中sleep()函式的單位是秒而不是毫秒,而在Windows環境下Sleep()函式是以毫秒為單位。這是兩者之間的區別。
Windows環境下計時延時函式程式碼如下:
#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{
double start, stop, durationTime;
start = clock();
Sleep(5 * 1000); //程式延時5s
stop = clock();
durationTime = ((double)(stop - start)) / CLK_TCK;
cout << "總耗時:" << durationTime << endl << endl;
return 0;
}
執行結果如圖所示:
Linux環境下程式碼如下:
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
double startTime,stopTime,durationTimeTime;
startTime=time(NULL);
sleep(5);
stopTime=time(NULL);
durationTimeTime = (double)difftime(stopTime,startTime);
cout << "耗時(time): " << durationTimeTime << " s" << endl;
return 0;
}
執行結果如圖所示:
感興趣的小夥伴可以在Linux環境下試一下clock()函式,目瞪口呆!!!