[C++11] 초간단 시간 측정 클래스

HourMeter.h

#pragma once
#include <iostream>
#include <chrono>

class HourMeter
{
public:
	HourMeter();
	~HourMeter();

	void startMeasure();
	void endMeasure();
	double getLatestDuration();
private:
	std::chrono::system_clock::time_point begin;
	std::chrono::system_clock::time_point end;
	std::chrono::duration<double> result_sec;
	bool isMeasuring;
};

 

HourMeter.cpp

#include "HourMeter.h"

HourMeter::HourMeter() :
	isMeasuring(false)
{
	printf("START HourMeter\n");
}

HourMeter::~HourMeter()
{
	printf("START ~HourMeter\n");
}

void HourMeter::startMeasure()
{
	if (isMeasuring == true) {
		printf("FAIL startMeasure; already measuring\n");
		throw std::runtime_error("startMeasure");
	}

	isMeasuring = true;
	begin = std::chrono::system_clock::now();
}

void HourMeter::endMeasure()
{
	if (isMeasuring == false) {
		printf("FAIL endMeasure; not measuring\n");
		throw std::runtime_error("endMeasure");
	}

	end = std::chrono::system_clock::now();
	result_sec = end - begin;
	isMeasuring = false;

	printf("수행시간: %lf\n", result_sec);
}

double HourMeter::getLatestDuration()
{
	return result_sec.count();
}

 

main.cpp

#include <iostream>
#include "HourMeter.h"
using namespace std;

void main() {
	HourMeter hourMeter;
	try {
		hourMeter.startMeasure();

		for (int i = 0; i < 2048; i++) {
			printf("Hello world\n");
		}

		hourMeter.endMeasure();
	}
	catch (std::exception & ex) {
		return;
	}

	printf("마지막 시간: %lf\n", hourMeter.getLatestDuration());
}

결과

HourMeter_Sample.zip
0.00MB