您的位置:首页 > 编程语言 > C语言/C++

如何在 C++ 程序中计算时间 .

2015-05-05 15:43 405 查看
1.如果在基于 Windows Win32 的程序(纯C++无法使用),即可以使用 GetTickCount() 函数实现。 精确到毫秒(ms)级。

[cpp]
view plaincopyprint?

DWORD dwStart = GetTickCount();

// 程序.......

DWORD dwEnd = GetTickCount();
DWORD dwTimeUsed = dwEnd - dwStart;

[cpp]
view plaincopyprint?

#include<stdio.h>
#include<time.h>
#include<conio.h>

int main()
{
time_t stime , etime ;
time( &stime ); // get start time

getch(); // Access

time( &etime ); // get end time

printf( "%ld/n" , etime - stime );
getch();

return 0;
}

#include<stdio.h>
#include<time.h>
#include<conio.h>

int main()
{
time_t stime , etime ;
time( &stime ); // get start time
getch(); // Access
time( &etime ); // get end time
printf( "%ld/n" , etime - stime );
getch();

return 0;
}


3. 使用CTimer类获取。(没有试用过)

[cpp]
view plaincopyprint?

class CTimer

{

public:

CTimer() {QueryPerformanceFrequency(&m_Frequency); Start();}

void Start() {QueryPerformanceCounter(&m_StartCount);}
double End() {LARGE_INTEGER CurrentCount;QueryPerformanceCounter(&CurrentCount); return double(CurrentCount.LowPart - m_StartCount.LowPart) / (double)m_Frequency.LowPart;}

private:

LARGE_INTEGER m_Frequency;
LARGE_INTEGER m_StartCount;
};

[cpp]
view plaincopyprint?

#include <iostream>
#include <ctime>

using namespace std;

int max(int x,int y)
{
return (x>y)?x:y;
}

int main()
{
const double begin = (double)clock()/CLK_TCK;
for(int i = 10000; i > 0; i--)
for(int j = 10000; j > 0; j--)

max(i, j);

const double end = (double)clock()/CLK_TCK;

cout <<begin<<" "<<end;
return 0;
}

#include <iostream>
#include <ctime>

using namespace std;

int max(int x,int y)
{
return (x>y)?x:y;
}

int main()
{
const double begin = (double)clock()/CLK_TCK;
for(int i = 10000; i > 0; i--)
for(int j = 10000; j > 0; j--)

max(i, j);

const double end = (double)clock()/CLK_TCK;

cout <<begin<<" "<<end;
return 0;
}


6. 最精确的方法,C++可直接调用,精确到 ms。

[cpp]
view plaincopyprint?

#include <ctime> //计时用的头文件

#include <iostream>

using namespace std;

int main()
{
time_t start,end,time;

start=clock();

for(int i=0;i<=100000;i++) cout << i << ' ';
cout << endl;

end=clock();
time=end-start;//这里的时间是计算机内部时间

cout << endl << ""time:" << time << endl;

system("pause");
return 0;
}

#include <ctime> //计时用的头文件
#include <iostream>

using namespace std;

int main()
{
time_t start,end,time;

start=clock();

for(int i=0;i<=100000;i++) cout << i << ' ';
cout << endl;

end=clock();
time=end-start;//这里的时间是计算机内部时间
cout << endl << ""time:" << time << endl;

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: