相应的封装类代码:
.h文件
#pragma once
#include<iostream>
#include <time.h>
#include<fstream>
using namespace std;
class testTxtOutput
{
private:
//开始计时
clock_t timeStart;
//结束计时
clock_t timeEnd;
//该段程序这一次执行时间
clock_t runTime;
//该段程序这一次执行的总时间
clock_t sumTime;
//平均执行时间
clock_t avgTime;
//最大执行时间
clock_t maxTime;
//统计执行帧的帧数
long countFrame;
public:
//开始计时
void openClocker(void);
//结束计时
void closeClocker();
//作为用户接口完成整个文件的读写
void writeToTxt(string funcName);
//计算相应的时间
void calculateTime();
public:
testTxtOutput(void);
~testTxtOutput(void);
};
.cpp文件
#include "StdAfx.h" #include "testTxtOutput.h" testTxtOutput::testTxtOutput(void): timeStart(0), timeEnd(0), runTime(0), sumTime(0), avgTime(0), maxTime(0), countFrame(0) { } testTxtOutput::~testTxtOutput(void) { } void testTxtOutput::openClocker(void) { timeStart = 0; runTime = 0; timeEnd = 0; timeStart = clock(); } void testTxtOutput::closeClocker(void) { timeEnd = clock(); } void testTxtOutput::writeToTxt(string funcName) { string cloneFunc =funcName; funcName += ".txt"; calculateTime(); ofstream fout; fout.open(funcName,ofstream::out | ofstream::app); fout<<cloneFunc.c_str()<<":第"<<countFrame<<"帧执行" <<" "<<"执行时间(ms):"<<runTime <<" "<<"最大执行时间(ms):"<<maxTime <<" "<<"平均执行时间(ms):"<<avgTime<<endl; } void testTxtOutput::calculateTime() { countFrame++; runTime = timeEnd - timeStart; sumTime += runTime; avgTime = sumTime/countFrame; maxTime = maxTime>runTime ? maxTime : runTime; }
main函数的调用:
// txtoutput.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include"testTxtOutput.h" int _tmain(int argc, _TCHAR* argv[]) { testTxtOutput out; out.writeToTxt("yangjie"); system("pause"); return 0; }
用法说明:
在需要的多次测试时间的函数执行文件中,包含该.h文件,并创建一个全局的实例。在测试函数的前面调用openClocker(),在函数的后面调用closeClocker()和writeToTxt()函数。