0%

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// #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

1
2
3
#define SUM(a,b)  (a+b)

#define MYDEBUG(...) fprintf(stderr, ##__VA_ARGS__)

usage

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

with class object

define

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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.