zoukankan      html  css  js  c++  java
  • C++ 求时差

    C++ 求时差的三种方法

    【1】标准C库方式

    示例代码

     1 #include <ctime>
     2 #include <iostream>
     3 using namespace std;
     4 
     5 void function()
     6 {
     7     int step = 100000000;
     8     while (step--);
     9 }
    10 
    11 int main()
    12 {
    13     clock_t start = clock();  //获取当前系统时间
    14 
    15     function();
    16 
    17     clock_t end = clock();
    18 
    19     double cost = ((double)(end - start)) / CLOCKS_PER_SEC;
    20 
    21     cout << "cost time : " << cost << endl;
    22 
    23     system("pause");
    24 }
    25 
    26 /* result:
    27 cost time : 0.166
    28 请按任意键继续. . .
    29 */

    【2】C++库方式

    C++11之后才引入

    示例代码:

     1 #include <chrono>
     2 #include <iostream>
     3 
     4 using namespace std;
     5 
     6 void function()
     7 {
     8     int step = 100000000;
     9     while (step--);
    10 }
    11 
    12 int main() 
    13 {
    14     auto beginTime = std::chrono::high_resolution_clock::now();
    15 
    16     function();
    17 
    18     auto endTime = std::chrono::high_resolution_clock::now();
    19     auto elapsedTime = std::chrono::duration_cast<std::chrono::microseconds>(endTime - beginTime);
    20 
    21     double cost = (double)elapsedTime.count();
    22 
    23     cout << "cost time : " << cost << endl;
    24 
    25     system("pause");
    26 }
    27 
    28 /* result:
    29 cost time : 164445
    30 请按任意键继续. . .
    31 */

    【3】windows API方式

    示例代码:

     1 #include <windows.h>
     2 #include <iostream>
     3 
     4 using namespace std;
     5 
     6 void function()
     7 {
     8     int step = 100000000;
     9     while (step--);
    10 }
    11 
    12 int main()
    13 {
    14     //DWORD dwStart = GetTickCount();
    15 
    16     ULONGLONG dwStart = GetTickCount64();
    17 
    18     function();
    19 
    20     ULONGLONG dwEnd = GetTickCount64();
    21     
    22     auto cost = (dwEnd - dwStart);
    23 
    24     cout << "cost time : " << cost << endl;
    25 
    26     system("pause");
    27 }
    28 
    29 /* result:
    30 cost time : 157
    31 请按任意键继续. . .
    32 */

    为什么第14行,我们把GetTickCount这个函数注释了呢?请参见Visual Studio 提示内容:

  • 相关阅读:
    微人事项目-mybatis-持久层
    通过外键连接多个表
    springioc
    Redis 消息中间件 ServiceStack.Redis 轻量级
    深度数据对接 链接服务器 数据传输
    sqlserver 抓取所有执行语句 SQL语句分析 死锁 抓取
    sqlserver 索引优化 CPU占用过高 执行分析 服务器检查
    sql server 远程备份 bak 删除
    冒泡排序
    多线程 异步 beginInvoke EndInvoke 使用
  • 原文地址:https://www.cnblogs.com/Braveliu/p/15635992.html
Copyright © 2011-2022 走看看