• C++如何使用宏定义来简化代码性能测试 | cpp macro like function to implement a performance profiler


    本文首发于个人博客https://kezunlin.me/post/65dc693d/,欢迎阅读最新内容!

    cpp macro like function to implement a performance profiler

    Guide

    macro expansions

    • name ===> quote as strings "xxx"

    • name, name ===> xxx

    • a ## b ===> concatenate the preceding and following tokens.
    // #name ===>  "xxx"
    // name,  ##name ===> xxx
    
    // ##name ===> concatenate  
    // #name ===>  quote as strings
    
    // a ## b ===>  concatenate the preceding and following tokens.
    
    
    #define QUOTE(name) #name
    #define CONCAT(x,y) x##y   // x ## y   space in ommited
    
    #define MACRO(name)  #name "foo"
    #define MACRO2(name) name "foo"
    #define MACRO3(name) ##name "foo"
    
    
    #define CAT(a, ...) a ## __VA_ARGS__
    
    #define IIF(c) CAT(IIF_, c)
    #define IIF_0(t, ...) __VA_ARGS__
    #define IIF_1(t, ...) t
    
    void macro_demo()
    {
    	QUOTE(test); // "test"
    	CONCAT(test, foo); // testfoo
    
    	MACRO(test); // "test" "foo"
    	MACRO2(test);// test "foo"
    	MACRO3(test);// test "foo"
    }
    

    macro function

    define

    #define SUM(a,b)  (a+b)
    
    #define MYDEBUG(...)   fprintf(stderr, ##__VA_ARGS__)
    

    usage

    int c = SUM(1,2);
    MYDEBUG("%d,%d 
    ",1,2);     /*   Becomes fprintf(stderr,"%d,%d 
    ",1,2);   */
    

    with class object

    define

    class profiler {
    public:
    	profiler(const char* func_name, unsigned int times = 1);
    	~profiler();
    
    	void start();
    	int stop();
    
    private:
    	boost::posix_time::ptime pt1;
    	boost::posix_time::ptime pt2;
    	const char * m_func_name;
    	int m_times = 1;
    };
    
    #define ONCE_PROFILER() profiler _profiler_instance##__LINE__(__FUNCTION__)
    
    #define BEGIN_PROFILE_ONE(name) profiler _profiler_##name(#name)
    #define BEGIN_PROFILE_TIMES(name,times) profiler _profiler_##name(#name,times)
    
    #define BEGIN_PROFILE(name,...) profiler _profiler_##name(#name, ##__VA_ARGS__)
    #define END_PROFILE(name)  _profiler_##name.stop()			
    

    usage

    void main()
    {
    
    BEGIN_PROFILE(LoadImage);
    
    	load_image();
    	
    END_PROFILE(LoadImage); 
        
        
    BEGIN_PROFILE_TIMES(ProcessImageTimes, 100);
    //BEGIN_PROFILE(ProcessImageTimes, 100);
    	for(int i=0; i<100;i++){
    		process_image();
    	}
    END_PROFILE(ProcessImageTimes);
    
    }
    

    Reference

    History

    • 20191010: created.

    Copyright

  • 相关阅读:
    音频文件的属性
    判断UITextField.text是否为空(转)
    digital audio properties
    对scrollView的属性contentSize contentOffset contentInset个人理解
    OC定义变参函数
    va_list、va_start、va_arg、va_end的原理与使用(转载)
    游标笔记
    oracle中删除重复数据
    IIS无法启动,错误代码127[转自Alibaba DBA Team]
    推进游标是Fetch不是Petch!~!
  • 原文地址:https://www.cnblogs.com/kezunlin/p/12026840.html
Copyright © 2020-2023  润新知