0
#include <iostream>
#include <chrono>

using namespace std;

class Time
{
    chrono::steady_clock::time_point start;

public:
    Time()
    {
        start = chrono::steady_clock::now();
    }

    ~Time()
    {
        auto end = chrono::steady_clock::now();
        std::chrono::duration<double> time = end-start;

        cout << "time " << time.count() << endl;
    }
};

void revstr(char* input)
{
    int length = strlen(input);
    int last_pos = length-1;
    for(int i = 0; i < length/2; i++)
    {
        char tmp = input[i];
        input[i] = input[last_pos - i];
        input[last_pos - i] = tmp;
    }
}

int main()
{
    Time t;
    char str[] = "abcd";
    cout << str << endl;
    revstr(str);
    cout << str << endl;
}

The above outputs:

time 7.708e-06

How should we turn that in milliseconds, nanoseconds or seconds?

I tried (replace std::chrono::duration<double> time = end-start;)

    std::chrono::duration<std::chrono::nanoseconds> time = end-start;

But it says:

A duration representation cannot be a duration.

KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • 1
    Like this: https://stackoverflow.com/a/28876539/4165552 with duration_cast – pptaszni Feb 07 '23 at 15:52
  • Your code shows `std::chrono::duration time`, but the error you show seems to think you wrote `std::chrono::duration time`. This error did not come from this code. – Drew Dormann Feb 07 '23 at 16:01

1 Answers1

4

Use std::chrono::duration_cast():

#include <chrono>
#include <iostream>

int main()
{
    std::chrono::duration<double> time{7.708e-06};

    auto nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(time);

    std::cout << nanos.count() << '\n';
}
Toby Speight
  • 27,591
  • 48
  • 66
  • 103