函数指针作为形参进行调用

代码

  • 两个代码均位于namespace作用域之内
  • addOne将传递进来的形参进行加一,然后返回
  • performance_test函数主要是想简化函数调用,两个形参,第一个表示循环的次数,第二个是带参数的函数指针,函数内部初始化start和end两个timeval的结构体实现时间差的相对计算,
#ifndef C___PERFOR_TEST_H
#define C___PERFOR_TEST_H
#pragma once

#include <sys/time.h>

#include "No1_track_instances.h"

namespace TEST{
    int addOne(int& x){
        return x+1;
    }
    void performance_test(int num,int fun(int& x)){
        struct timeval start;
        struct timeval end;
        gettimeofday(&start, NULL);//开始计时
        int sum = 0;
        for(int i=0;i<num;++i){
            sum += fun(i);
        }
        std::cout << "sum= " << sum <<std::endl;
        gettimeofday(&end, NULL);//结束计时
        std::cout<<"总计用时: " << (((end.tv_sec - start.tv_sec)*1000000 +
                     (end.tv_usec - start.tv_usec)))/1000000 <<std::endl;
    }

}

#endif //C___PERFOR_TEST_H

函数调用

  • TEST::performance_test(15,TEST::addOne);
  • 调用性能测试代码,传递循环次数和函数
#include <iostream>
#include <sys/time.h>

#include "No1_track_instances.h"
#include "test.h"

int main() {
//    TRACK_INSTANCES::Trace::traceIsActive = false;//关闭跟踪
    TEST::performance_test(15,TEST::addOne);
    return 0;
}

 参考链接

猜你喜欢

转载自blog.csdn.net/CHYabc123456hh/article/details/127763796