经常遇到一些情况,需要计算代码执行的效率,所以要进行多次循环得到,
用得多了,就发现把这段代码封装起来很合适,且很实用。
代码如下:
/*
* ccTime.h
* c++_common_codes
*
* Created by xichen on 12-2-18.
* Copyright 2012 cc_team. All rights reserved.
*
*/
#ifndef CC_TIME_H
#define CC_TIME_H
#include <ctime>
#define MACRO_TIME_BEGIN(loopCount) \
{ \
clock_t begin, end; \
begin = clock(); \
for(int i = 0; i < (loopCount); ++i) \
{ \
#define MACRO_TIME_END \
} \
end = clock(); \
printf("\ntime is %f s\n", (double)(end - begin) / CLOCKS_PER_SEC); \
}
#endif
测试实例:
#include "ccTime.h"
#include <iostream>
void ccTestMacroTime()
{
#if 1
int loopCount = 100;
MACRO_TIME_BEGIN(loopCount)
for(int i = 0; i < 1; ++i)
{
std::cout << i * i << std::endl;
}
MACRO_TIME_END
#endif
}
测试结果:
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
time is 0.000416 s