posts - 150,comments - 9,views - 12万

新增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   clayyjh  阅读(2355)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示