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