(1)clock()函数用法

void timeConsume()
{
double start,stop,durationTime;
start = clock();
/*

...代码片段

*/
stop = clock();

durationTime = ((double)(stop-start))/CLK_TCK;
cout << "程序耗时:" << durationTime << " s" << endl;
}

(2)time()函数用法

void timeConsume()
{
double start,stop,durationTime;
start = time(NULL);
/*

...代码片段

*/
stop = time(NULL);

durationTime = (double)difftime(stop, start);
cout << "程序耗时:" << durationTime << " s" << endl;
}

(3)延时函数

 

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;
}