打印函数调用时间

raii可以实现,通过new delete控制调用前后,很懒,只想加几个字符,不想换行

snippet mlt
#include <sys/time.h>

#define MLLOG printf
#ifndef MLLOG
#error "please define MLLOG"
#endif

struct MLT{
        MLT(struct timeval start_time, const char* label_tag)
        :t_start(start_time), label(label_tag)
        {
        }

        template <typename T>
        MLT& operator = (T)
        {
            return *this;
        }

        ~MLT()
        {
            gettimeofday(&t_end, 0);
            long time_diff = (t_end.tv_sec - t_start.tv_sec)*1000 + (t_end.tv_usec - t_start.tv_usec)/1000;
            MLLOG("%s cost time is %ld ms\n", label, time_diff);
        }
private:
    struct timeval t_start;
    struct timeval t_end;
    const char* label;
};

MLT mlt_helper(struct timeval start_time, const char* label_tag)
{

    return MLT(start_time, label_tag);
}

// caNNot use for void return functions
// and seems tedious
#define mlt(f)    struct timeval t_start; \
                  gettimeofday(&t_start, 0); \
                  mlt_helper(t_start, #f) = \


// cannot use for void return functions
#define mt        struct timeval t_start; \
                  gettimeofday(&t_start, 0); \
                  mlt_helper(t_start, "") = \
 

测试:

int f(void)
{
    float k = 0.0;
    for(auto i = 0; i < 10010; i++)
    for(auto m = 0; m < 10090; m++)
    {
        float j = ((float)i*4.19)/4.342;

        k += j;
    }
}
 

int main(int argc, char* argv[])
{
mlt(xxx)
f();

cout << "after " << endl;

    return 0;
}
有两个问题,void不能作为operator=的参数,所以benchmark的函数必须有返回值,mlt不能直接取f 的名称,导致要写个(),比较烦。懒。

猜你喜欢

转载自blog.csdn.net/starpicker/article/details/82706201
今日推荐