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 提示内容:

  • 相关阅读:
    【题解】Luogu P3217 [HNOI2011]数矩形
    【题解】 Luogu P4312 / SP4155 [COCI 2009] OTOCI / 极地旅行社
    珂朵莉树详解
    数学手法之线性基
    【题解】luogu P3386 【模板】二分图匹配
    【题解】Luogu P2146 [NOI2015]软件包管理器
    css 垂直居中方法汇总
    css3中什么时候用transition什么时候用animation实现动画
    前端进阶(8)
    前端进阶(12)
  • 原文地址:https://www.cnblogs.com/Braveliu/p/15635992.html
Copyright © 2011-2022 走看看