2025年4月8日 星期二 乙巳(蛇)年 正月初九 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > VC/VC++

C++ 求时差的三种方法

时间:04-09来源:作者:点击数:59

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

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门