在进行格式化输出时,常常需对多个函数执行相同操作,此时会产生大量重复代码。为保证代码的简洁、易读,此时可对输出函数进行封装,即使之变成调用函数的函数。
代码示例:
此时想对实现同一需求的多个函数,进行计时比较。
(记录程序运行时间的代码可见博客C/C++记录程序运行时间)
#include <iostream>
#include <time.h>
#include <functional>//bind
using namespace std;
template<typename F>
void calTime(F f) {//作为模板类型传入
clock_t t;
t = clock();
auto&& res = f();//调用函数
t = clock() - t;
printf("result=%ld,time=% lf s\n", res, ((float)t) / CLOCKS_PER_SEC);//统一输出
}
int main() {
calTime(std::bind(&calculatePlanA, 99999999));//调用函数calculatePlanA,传入参数99999999
calTime(std::bind(&calculatePlanB, 99999999));//调用函数calculatePlanB,传入参数99999999
return 0;
}
运行结果:
(函数具体功能为求1~n的和)