最近看了<<重构:改善现有代码...>>里面的JAVA人写了一个测试用例,吹嘘用到了JAVA反射等"高级功能",我也写一些测试代码看看.
首先是代表性能数据的类:
class CapabilityCount
{
public:
static void Out();
char* m_clue;
CapabilityCount *m_pre;
DWORD m_frequency;
DWORD m_times;
static CapabilityCount*head;
CapabilityCount(char* clue);
};
CapabilityCount*CapabilityCount::head=0;
CapabilityCount::CapabilityCount(char*clue)
{
m_pre=head;
head=this;
m_clue=clue;//连成一片,接受一个字符串作输出标识.
}
void CapabilityCount::Out()//输出到文本文件
{
std::fstream out;
CTime time;
out.open ("d:\\testcount.txt",std::ios_base::ate|std::ios_base::out);
ASSERT(out.is_open ());
time=CTime::GetCurrentTime();
out<<"is begin write in"<<time.GetDay() <<" : "
<<time.GetHour ()<<" : "
<<time.GetMinute ()<<"\n";
CapabilityCount *psearch=head;
while(psearch)
{
out<<"type:"<<psearch->m_clue<<"all time(milliseconds):"<<psearch->m_times
<<" be call frequency :"<<psearch->m_frequency
<<" average time(milliseconds):"
<<psearch->m_times /psearch->m_frequency<<"\n\n";
psearch=psearch->m_pre ;
}
}
然后是一个"改动者",负责更新CapabilityCount类
class CapabilityCountHelper
{
DWORD m_begintime;
CapabilityCount &m_supervised;
public:
CapabilityCountHelper(CapabilityCount& in);
~CapabilityCountHelper();
};
CapabilityCountHelper::CapabilityCountHelper(CapabilityCount& in):
m_supervised(in)
{
m_begintime=GetTickCount();
++m_supervised.m_frequency;//被调用的次数
}
CapabilityCountHelper::~CapabilityCountHelper()
{
DWORD spend=GetTickCount()-m_begintime;
m_supervised.m_times +=spend;//花掉的总时间
}
知道怎么用吧?
在要测试的函数前加上
static CapabilityCount //一定要有static哦
CapabilityCountInstance("function name or else");
CapabilityCountHelper CapabilityCountHelperInstance(CapabilityCountInstance);
嫌麻烦?
#define KILL_BILL__KILL_BILL__KILL_BILL(clue) static CapabilityCount \
CapabilityCountInstance(clue); \
CapabilityCountHelper CapabilityCountHelperInstance(CapabilityCountInstance) \
最近想看<<杀死比尔>>,虽然杀的不是我想的:(
你可以用更精确的时间函数来测试.不过这不关我事;
你也可以在内联函数中或甚至上面的CapabilityCount::Out函数中加入
KILL_BILL__KILL_BILL__KILL_BILL("CapabilityCount::Out");
发生什么事可不关我事:(
文章来源于领测软件测试网 https://www.ltesting.net/