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

  • 相关阅读:
    Hdu 1257 最少拦截系统
    Hdu 1404 Digital Deletions
    Hdu 1079 Calendar Game
    Hdu 1158 Employment Planning(DP)
    Hdu 1116 Play on Words
    Hdu 1258 Sum It Up
    Hdu 1175 连连看(DFS)
    Hdu 3635 Dragon Balls (并查集)
    Hdu 1829 A Bug's Life
    Hdu 1181 变形课
  • 原文地址:https://www.cnblogs.com/Braveliu/p/15635992.html
Copyright © 2011-2022 走看看