使用C++獲取邏輯執(zhí)行毫秒數(shù)的方法
更新時間:2024年02月05日 11:05:46 作者:llxtxwd
這篇文章主要為大家詳細(xì)介紹了如何使用C++獲取邏輯執(zhí)行毫秒數(shù)的方法,文中借助c++11提供的steady_clock,實(shí)現(xiàn)了精確獲取邏輯執(zhí)行時間的方法,需要的可以參考下
借助c++11提供的steady_clock
,實(shí)現(xiàn)了精確獲取邏輯執(zhí)行時間的方法,原理:當(dāng)前時間 - 開始時間。
工具類文件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(); }; // 重置當(dāng)前時間 // 默認(rèn)輸出毫秒,如果函數(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對象,同時記錄當(dāng)前時間 Case1(); // 需要獲取執(zhí)行時間的邏輯 cout << "cost1 = "<< timer.cost(); // 得出執(zhí)行時間 timer.reset(); // 重置初始時間 Case2(); // 另一個需要獲取執(zhí)行時間的邏輯 cout << "cost2 = "<< timer.cost(); // 得出執(zhí)行時間
以上就是使用C++獲取邏輯執(zhí)行毫秒數(shù)的方法的詳細(xì)內(nèi)容,更多關(guān)于C++獲取邏輯執(zhí)行毫秒數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C++中實(shí)現(xiàn)隊(duì)列類鏈?zhǔn)酱鎯εc棧類鏈?zhǔn)酱鎯Φ拇a示例
這篇文章主要介紹了C++中實(shí)現(xiàn)隊(duì)列類鏈?zhǔn)酱鎯εc棧類鏈?zhǔn)酱鎯Φ拇a示例,通過注釋來說明,直接上代碼,簡單粗暴XD 需要的朋友可以參考下2016-03-03C++生成格式化的標(biāo)準(zhǔn)字符串實(shí)例代碼
這篇文章主要給大家介紹了關(guān)于C++生成格式化的標(biāo)準(zhǔn)字符串的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用C++具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09Matlab實(shí)現(xiàn)三維投影繪制的示例代碼
這篇文章系小編為大家?guī)砹艘粋€三維投影繪制函數(shù)(三視圖繪制),函數(shù)支持三維曲線、曲面、三維多邊形、參數(shù)方程曲線、參數(shù)方程曲面的投影繪制,需要的可以參考一下2022-08-08