Timing in an elegant way in c++

后端 未结 4 493
难免孤独
难免孤独 2021-01-03 01:31

I am interested in timing the execution time of a free function or a member function (template or not). Call TheFunc the function in question, its call being



        
4条回答
  •  轮回少年
    2021-01-03 02:02

    I'm a fan of using RAII wrappers for this type of stuff.

    The following example is a little verbose but it's more flexible in that it works with arbitrary scopes instead of being limited to a single function call:

    class timing_context {
    public:
      std::map timings;
    };
    
    class timer {
    public:
      timer(timing_context& ctx, std::string name)
        : ctx(ctx),
          name(name),
          start(std::clock()) {}
    
      ~timer() {
        ctx.timings[name] = static_cast(std::clock() - start) / static_cast(CLOCKS_PER_SEC);
      }
    
      timing_context& ctx;
      std::string name;
      std::clock_t start;
    };
    
    timing_context ctx;
    
    int main() {
      timer_total(ctx, "total");
      {
        timer t(ctx, "foo");
        // Do foo
      }
    
      {
        timer t(ctx, "bar");
        // Do bar
      }
      // Access ctx.timings
    }
    

    The downside is that you might end up with a lot of scopes that only serve to destroy the timing object.

    This might or might not satisfy your requirements as your request was a little vague but it illustrates how using RAII semantics can make for some really nice reusable and clean code. It can probably be modified to look a lot better too!

提交回复
热议问题