Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a variable from a destructor

Tags:

c++

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?


1 Answers

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
}
like image 70
Ted Lyngmo Avatar answered May 09 '26 21:05

Ted Lyngmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!