统计代码运行时间的方法

0. C++代码运行时间统计(精确到纳秒(ns)):

#include <iostream>
#include <chrono>
#include <iomanip>    
using namespace std;

void main()
{
    auto start = chrono::high_resolution_clock::now();    //开始时间

    double db = 0;    //此处放代码
    for (int i = 0; i < 100000; i++)
    {
        db += i;
    }

    auto end = chrono::high_resolution_clock::now();    //结束时间
    __int64 duration = (end - start).count();
    cout << "程序运行时间:" << setprecision(10) << duration / 1000000000.0 << "s"
        << "" << duration / 1000000.0 << "ms" 
        << "" << duration / 1000.0 << "us"
        << endl;

    cin.get();
}

    运行结果:

1. C++代码运行时间统计:

#include <iostream>
#include <thread>    //包含此头文件

using namespace std;

void main()
{
    clock_t start = clock();


    for (int i = 0; i < 1000; i++)
    {
        cout << "hello" << endl;
    }


    clock_t end = clock();

    cout << "程序运行时间:" << end - start << "ms" << endl;
    cin.get();
}

2. C/C++中计算代码运行时间:

方法一:单位ms

#include<iostream>  
#include<Windows.h>  

using namespace std;

int main()
{
    DWORD start_time = GetTickCount();    //开始时间;    GetTickCount()获取从操作系统启动开始所经过的毫秒数,返回值是DWORD类型

    for (int i = 0; i < 100000000; i++)
    {
        i++;
    }

    DWORD end_time = GetTickCount();    //结束时间;    

    cout << "运行时间为:" << (end_time - start_time) << "ms" << endl;

    system("pause");
    return 0;
}

方法二:单位s

#include <iostream>   
#include <ctime>  

using namespace std;

void main(void)
{
    clock_t start, finish;
    double  duration;

    start = clock();    //开始时间;    clock()是C/C++中的计时函数,而与其相关的数据类型是clock_t

    for(int i=0;i<100;i++)
        cout << "hello world" << endl;

    finish = clock();    //结束时间;

    duration = (double)(finish - start) / CLOCKS_PER_SEC;    //代码运行时间

    cout <<"代码运行时间为:"<< duration << " s" << endl;

    system("pause");
}

 

posted @ 2018-11-20 16:13  博观&约取  阅读(1632)  评论(0编辑  收藏  举报