String-interning at compiletime for profiling

前端 未结 2 755
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-20 07:51

Context

I am working on an instrumenting profiler, that enables you to name different measurements by string. So for example:

MEASURE_SCOPE(text_re         


        
2条回答
  •  执笔经年
    2020-12-20 08:49

    I can only guess what you mean, because you don't give enough details, and they matter a lot.

    A possible approach is to generate some ad-hoc C or C++ code with your own generator. Remember that some C or C++ code of your project can be generated (this is a crude form or metaprogramming; Qt moc, RPCGEN, bison, SWIG are typical examples of C++ or C generators, but you can easily make your own one, see here; perhaps with the help of some scripting language like Python, Guile, AWK, ..., or even in C++), and your build automation could handle that (e.g. some as-hoc rule or recipe in your Makefile).

    Then you could write a very simple generating program collecting all occurrences of MEASURE_SCOPE and MEASURE_START, MEASURE_STOP macro invocations in your code (*.cpp files of your project). This is quite simple to code: you could read line by line all .cpp files and look for MEASURE_SCOPE (etc...) followed by spaces then by ( in them.

    That generating program -dealing with your interned strings- might emit a large header file measure-generated.h with e.g. things like

    // in generated header
    #define MEASURE_POINT_system_call 1
    #define MEASURE_POINT_password_hashing 2
    

    (maybe you want to generate some large enum instead)

    and it would also emit a measure-generated-array.cpp file like

    // generated code
    const char* measure_array[] = {
      NULL,
      "system_call",
      "password_hashing",
      /// etc....
      NULL,
    };
    

    And then you could in some of your headers

    #define MEASURE_SCOPE(X) measure_array[MEASURE_POINT_##X]
    

    etc, using preprocessor tricks like stringizing and/or concatenation

    See also this.

    This would require building the name-array at compile time, effectively interning the strings. Is this possible?

    Yes, of course. Do that in your own C++ generator which knows all your project *.cpp files like I suggested. You can generate C++ files at build time.

提交回复
热议问题