计算程序运行的时间

来源:互联网 发布:熊猫计划软件链接 编辑:程序博客网 时间:2024/05/01 00:53
1.这个是windows里面常用来计算程序运行时间的函数;
DWORD dwStart = GetTickCount();
//这里运行你的程序代码
DWORD dwEnd = GetTickCount();
则(dwEnd-dwStart)就是你的程序运行时间, 以毫秒为单位

这个函数只精确到55ms,1个tick就是55ms。


#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char* argv[])
{
DWORD start, end;

start = GetTickCount();
for(int i=0;i<1000;i++)
cout<<"you are a good child!"<<endl;   //your code
end = GetTickCount()-start;
cout<<end<<endl;
    return 0;
}

2
timeGetTime()基本等于GetTickCount(),但是精度更高
DWORD dwStart = timeGetTime();

//这里运行你的程序代码

DWORD dwEnd = timeGetTime();

则(dwEnd-dwStart)就是你的程序运行时间, 以毫秒为单位
虽然返回的值单位应该是ms,但传说精度只有10ms。

#include <iostream>
#include <windows.h>
#pragma comment(lib,"winmm.lib")

using namespace std;
int main(int argc, char* argv[])
{
DWORD start, end;

start = timeGetTime();
for(int i=0;i<100;i++)
cout<<"you are a good child!"<<endl;
end = timeGetTime()-start;
cout<<end<<endl;
    return 0;
}

3
用clock()函数,得到系统启动以后的毫秒级时间,然后除以CLOCKS_PER_SEC,就可以换成“秒”,标准c函数。
clock_t clock ( void );

#include <time.h>
clock_t t = clock();
long sec = t / CLOCKS_PER_SEC;
他是记录时钟周期的,实现看来不会很精确,需要试验验证;

#include<iostream>
#include<ctime> //<time.h>
using   namespace   std;
int   main()
{
    time_t   begin,end;

    double duration;
    begin=clock();
    //这里加上你的代码
    end=clock();

    duration=double(end-begin)/CLOCKS_PER_SEC;
    cout<<"runtime:   "<<duration<<endl;
}

1 0
原创粉丝点击