新增chrono计算耗时

#include <iostream>
#include <chrono>
#include <unistd.h>
 
using namespace std;
 
// 测量 C++ 程序运行时间的主函数
// 使用 Chrono 库
int main()
{
    auto start = chrono::steady_clock::now();
 
    // 在这里做一些事情
    sleep(3);
 
    auto end = chrono::steady_clock::now();
 
    cout << "Elapsed time in nanoseconds: "
        << chrono::duration_cast<chrono::nanoseconds>(end - start).count()
        << " ns" << endl;
 
    cout << "Elapsed time in microseconds: "
        << chrono::duration_cast<chrono::microseconds>(end - start).count()
        << " µs" << endl;
 
    cout << "Elapsed time in milliseconds: "
        << chrono::duration_cast<chrono::milliseconds>(end - start).count()
        << " ms" << endl;
 
    cout << "Elapsed time in seconds: "
        << chrono::duration_cast<chrono::seconds>(end - start).count()
        << " sec";
 
    return 0;
}

 

 

 

 

 

1. 精度为毫秒级

  clock() 返回程序从开启这个进程到程序中调用clock()函数之间的CPU始终周期;

 CLOCKS_PER_SEC 为CPU一秒钟的时钟周期数
#include <time.h>
#inlclude <stdio.h>

int main()
{
    clock_t start, end;
    start = clock();
    ···
    ···
    ···
    end = clock();
    printf("程序耗时:%lf", (double)(end - start)/CLOCKS_PER_SEC);  
    return 0;
}

2. 精度为微秒级

    QueryPerformanceCounter()是一个Windows API,所需头文件为<windows.h>。

    这个函数返回高精确度性能计数器的值,它可以以微秒为单位计时.但是QueryPerformanceCounter()确切的精确计       时的最小单位是与系统有关的, 所以,必须要查询系统以得到QueryPerformanceCounter()返回的嘀哒声的频率.           QueryPerformanceFrequency() 提供了这个频率值,返回每秒嘀哒声的个数。

#include <windows.h>
#include <stdio.h>
int main()
{
    LARGE_INTEGER t1, t2, tc;
    QueryPerformanceFrequency(&tc);
    QueryPerformanceCounter(&t1);
    ···
    ···
    ···
    QueryPerformanceCounter(&t2);
    printf("程序耗时:%lf",(double)(t2.QuadPart-t1.QuadPart)/(double)tc.QuadPart);
return 0;
}
posted on 2021-03-12 22:04  clayyjh  阅读(2302)  评论(0编辑  收藏  举报