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

精确到毫秒(ms)

#include<stdio.h>
#include<time.h>   //用到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<stdio.h>
#include <windows.h>
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;
}
上一篇:JVM学习笔记——类加载过程


下一篇:树状数组