c语言/c++计算程序运行时间

精确到毫秒(ms)

#include
#include   //用到clock()函数
int main() {
    int begintime,endtime;
    int i = 0;
    int a[1002];
    begintime=clock();  //计时开始
    

        /*
        代码块
        */

    endtime = clock();  //计时结束
    printf("\n\nRunning Time:%dms\n", endtime-begintime);
    return 0;
}

精确到微秒(us)

#include
#include 
int main() {
    int a[10002];
    int i = 0;
    double run_time;
    _LARGE_INTEGER time_start;  //开始时间
    _LARGE_INTEGER time_over;   //结束时间
    double dqFreq;      //计时器频率
    LARGE_INTEGER f;    //计时器频率
    QueryPerformanceFrequency(&f);
    dqFreq=(double)f.QuadPart;
    QueryPerformanceCounter(&time_start);   //计时开始
    

        /*
        代码句
        */


    QueryPerformanceCounter(&time_over);    //计时结束
    run_time=1000000*(time_over.QuadPart-time_start.QuadPart)/dqFreq;
    //乘以1000000把单位由秒化为微秒,精度为1000 000/(cpu主频)微秒
    printf("\nrun_time:%fus\n",run_time);
    return 0;
}

测试时间与n的关系

采用的方式是简单的y++

时间复杂度为O(n)
执行9次操作

#include
#include 
#include 
#define ll long long
using namespace std;
int main() {


    ll x=1000;
    for(int i=1;i<10;i++){
        double run_time;
        LARGE_INTEGER time_start;  //开始时间
        LARGE_INTEGER time_over;   //结束时间
        double dqFreq;      //计时器频率
        LARGE_INTEGER f;    //计时器频率
        QueryPerformanceFrequency(&f);
        dqFreq=(double)f.QuadPart;
        QueryPerformanceCounter(&time_start);   //计时开始

        //开始操作
        ll y=0;
        for(ll j=1;j<=x;j++){
            y++;
        }
        x*=10;
        //结束操作

        QueryPerformanceCounter(&time_over);    //计时结束
        run_time=1000000*(time_over.QuadPart-time_start.QuadPart)/dqFreq;
        //乘以1000000把单位由秒化为微秒,精度为1000 000/(cpu主频)微秒
        printf("\nrun_time:%fus\n",run_time);
    }
    return 0;
}

最后输出的是

run_time:1.924813us

run_time:19.248130us

run_time:192.802098us

run_time:1950.156327us

run_time:18903.267242us

run_time:179787.474985us

run_time:1795408.102051us

run_time:18517596.319244us

run_time:186273317.344554us

明显地发现,呈现着线性的关系,n增大10倍后,时间也是增大10倍,所以时间复杂度可以用O(n)线性表示

你可能感兴趣的:(c语言/c++计算程序运行时间)