Home > OS >  Best way to design a time-measuring structure in C ?
Best way to design a time-measuring structure in C ?

Time:06-29

I am struggling to do the following in the best way possible:

I have to measure the execution time of a C functionality implemented in C . I have access to the code, so I can extend/modify it. The structure of what I have to do would be something like:

for (int k=0;k<nbatches;k  ) {
   //Set parameters from config file
   parameters=readFromFile(k);
   s=startTime();
   for(int i=0;i<niters;i  )
   {
       o=namespacefoo::foo(parameters);
       writeToFile(o,i,k);
   }
   e=endTime();
   times[k]=e-s/niters;
}
return times;

I am quite sure that I will have to use the same structure to measure other functionalities from other namespaces.

I am not sure if it makes sense to transform each functionality into a derived-class from a base-class. Each derived-class would implement the virtual read/write wrappers and there would be a measuring function, non-member non-friend convenience function, which would implement my previous structures. Also, the number/type of the parameters is also dependent on each derived-class. Maybe I would have to do the same derived-class strategy for the parameters too. Finally a factory function would set everything.

Does this seem very cumbersome for the simple task I want to solve? I am sure this is not the first time that someone needs something like this and I do not want to rediscover the wheel.

Thanks

CodePudding user response:

The std::chrono library gives you all what you need.

Please see here.

With that, you could write a very simple wrapper for your requirement.

We will define a timer class with a start and a stop function. "start" uses now to get the current time. "stop" will calculate the elapsed time, between start and the time, when "stop" was called.

Additionally, we override the inserter operator << to allow for easy output.

Please see the simple example below:

#include <iostream>
#include <fstream>
#include <chrono>

class Timer {
    std::chrono::time_point<std::chrono::high_resolution_clock> startTime{};
    long long elapsedTime{};
public:
    void start() { startTime = std::chrono::high_resolution_clock::now(); }
    void stop() { elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - startTime).count(); }
    friend std::ostream& operator << (std::ostream& os, const Timer& t) { return os << t.elapsedTime; }
};

// Example code
int main() {

    Timer t;            // Define/Instantiate timer
    t.start();          // Start Timer

    // Burn some time:
    for (unsigned i{}; i < 1000;   i) std::cout << i << '\n';

    t.stop();           // Stop timer

    // Show result
    std::cout << "\n\nDuration for operation was:\t " << t << " ms\n";
}
  • Related