本文首发于个人博客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 \n",1,2); /* Becomes fprintf(stderr,"%d,%d \n",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
- Post author: kezunlin
- Post link: https://kezunlin.me/post/65dc693d/
- Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.
来源:https://www.cnblogs.com/kezunlin/p/12026840.html