0. C++代碼運行時間統計(精確到納秒(ns)):ios
#include <iostream> #include <chrono> #include <iomanip> using namespace std; void main() { auto start = chrono::high_resolution_clock::now(); //開始時間 double db = 0; //此處放代碼 for (int i = 0; i < 100000; i++) { db += i; } auto end = chrono::high_resolution_clock::now(); //結束時間 __int64 duration = (end - start).count(); cout << "程序運行時間:" << setprecision(10) << duration / 1000000000.0 << "s" << "; " << duration / 1000000.0 << "ms" << "; " << duration / 1000.0 << "us" << endl; cin.get(); }
運行結果:函數
1. C++代碼運行時間統計:spa
#include <iostream> #include <thread> //包含此頭文件 using namespace std; void main() { clock_t start = clock(); for (int i = 0; i < 1000; i++) { cout << "hello" << endl; } clock_t end = clock(); cout << "程序運行時間:" << end - start << "ms" << endl; cin.get(); }
2. C/C++中計算代碼運行時間:操作系統
方法一:單位mscode
#include<iostream> #include<Windows.h> using namespace std; int main() { DWORD start_time = GetTickCount(); //開始時間; GetTickCount()獲取從操做系統啓動開始所通過的毫秒數,返回值是DWORD類型 for (int i = 0; i < 100000000; i++) { i++; } DWORD end_time = GetTickCount(); //結束時間; cout << "運行時間爲:" << (end_time - start_time) << "ms" << endl; system("pause"); return 0; }
方法二:單位sblog
#include <iostream> #include <ctime> using namespace std; void main(void) { clock_t start, finish; double duration; start = clock(); //開始時間; clock()是C/C++中的計時函數,而與其相關的數據類型是clock_t for(int i=0;i<100;i++) cout << "hello world" << endl; finish = clock(); //結束時間; duration = (double)(finish - start) / CLOCKS_PER_SEC; //代碼運行時間 cout <<"代碼運行時間爲:"<< duration << " s" << endl; system("pause"); }