Home > Software engineering >  How to return a variable from a destructor
How to return a variable from a destructor

Time:05-23

So I have a struct called timer which determines how much time did a block of code take to execute and complete and I'm going to run few benchmarks on my sorting algorithm and take the average value of time it took for each sorting algorithm.

struct Example{
    std::chrono::time_point<std::chrono::steady_clock> start, end;
    Example() {
        start = std::chrono::high_resolution_clock::now();
    }
    ~Example() {
        end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<float>  duration = end - start;
        float ms = duration.count() * 1000.0f;
        std::cout << ms << " miliseconds\n";
        // a way to return ms?
    }
};

However, I was not able to find a way to get the variable ms out of the destructor and assign it to something after measuring the time. Is there any way to get it out or can I write my struct in a better way?

CodePudding user response:

You can't return anything from the deststructor but you can assign the value to a variable that you supply to Example upon creation. Example:

#include <chrono>
#include <iostream>

template <class Clock = std::chrono::steady_clock>
struct Example {
    std::chrono::time_point<Clock> start;
    std::chrono::duration<float>& duration;         // a reference

    Example(std::chrono::duration<float>& dur) :    // take the duration as an argument
        start(Clock::now()),
        duration(dur)
    {}

    ~Example() {
        auto end = Clock::now();
        duration = end - start; // assign the value
    }
};

int main() {
    std::chrono::duration<float> duration;
    {
        Example<> x(duration);
    }
    std::cout << duration.count() << '\n';  // read it afterawrds
}
  •  Tags:  
  • c
  • Related