使用C++獲取邏輯執(zhí)行毫秒數(shù)的方法
更新時間:2024年02月05日 11:05:46 作者:llxtxwd
這篇文章主要為大家詳細介紹了如何使用C++獲取邏輯執(zhí)行毫秒數(shù)的方法,文中借助c++11提供的steady_clock,實現(xiàn)了精確獲取邏輯執(zhí)行時間的方法,需要的可以參考下
借助c++11提供的steady_clock
,實現(xiàn)了精確獲取邏輯執(zhí)行時間的方法,原理:當前時間 - 開始時間。
工具類文件Timer.h:
#pragma once #include <chrono> using namespace std::chrono; // 記錄執(zhí)行代碼消耗時間 class Timer { public: Timer() :m_begin(steady_clock::now()) {}; // 初始化列表 void reset() { m_begin = steady_clock::now(); }; // 重置當前時間 // 默認輸出毫秒,如果函數(shù)邏輯簡單建議使用微秒 long long cost() const { return duration_cast<std::chrono::milliseconds>(steady_clock::now() - m_begin).count(); } // 微秒 long long cost_micro() const { return duration_cast<std::chrono::microseconds>(steady_clock::now() - m_begin).count(); } // 秒 long long cost_seconds() const { return duration_cast<std::chrono::seconds>(steady_clock::now() - m_begin).count(); } private: time_point<steady_clock> m_begin; };
包含工具頭文件就可以使用了:
#include"Timer.h" Timer timer; // 構(gòu)造Timer對象,同時記錄當前時間 Case1(); // 需要獲取執(zhí)行時間的邏輯 cout << "cost1 = "<< timer.cost(); // 得出執(zhí)行時間 timer.reset(); // 重置初始時間 Case2(); // 另一個需要獲取執(zhí)行時間的邏輯 cout << "cost2 = "<< timer.cost(); // 得出執(zhí)行時間
以上就是使用C++獲取邏輯執(zhí)行毫秒數(shù)的方法的詳細內(nèi)容,更多關于C++獲取邏輯執(zhí)行毫秒數(shù)的資料請關注腳本之家其它相關文章!
相關文章
C++中實現(xiàn)隊列類鏈式存儲與棧類鏈式存儲的代碼示例
這篇文章主要介紹了C++中實現(xiàn)隊列類鏈式存儲與棧類鏈式存儲的代碼示例,通過注釋來說明,直接上代碼,簡單粗暴XD 需要的朋友可以參考下2016-03-03