8 Ways to Measure Execution Time in C/C++

转载自

https://levelup.gitconnected.com/8-ways-to-measure-execution-time-in-c-c-48634458d0f9

#include <chrono>
class ElapsedTimer
{
public:
	void start() {
		begin = std::chrono::steady_clock::now();
	}
	int64_t nsElapsed() {
		std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
		return std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count();//[ns]
	}
	int64_t µsElapsed() {
		std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
		return std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count();//[µs]
	}
	int64_t msElapsed() {
		std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
		return std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count();//[ms]
	}
	int64_t sElapsed() {
		std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
		return std::chrono::duration_cast<std::chrono::seconds>(end - begin).count();//[s]
	}
	double_t msElapsedf() {
		std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
		return (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000.0;//[ms .]
	}
	double_t sElapsedf() {
		std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
		return (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000000.0;//[s .]
	}
private:
	std::chrono::steady_clock::time_point begin;
};
posted @ 2020-12-22 17:13  學海無涯  阅读(92)  评论(0编辑  收藏  举报