siery siery - 3 months ago 13
C++ Question

counting time point in chrono library

I'm using chrono library for the first time so please be lenient C:. So I want to write a simple get time function that return just processor tics with chrono. But when i try to use

clock()
function to get the value from a time point initialized with
steady_clock::now()
, gcc says that
time_point
doesn't contain
count()
member.

/home/siery/Documents/Project/ChangeStateMachine/main.cpp|41|error: ‘struct std::chrono::time_point<std::chrono::_V2::steady_clock, std::chrono::duration<long long int, std::ratio<1ll, 1000000000ll> > >’ has no member named ‘count’|


Here is the code:

float GetTime()
{
float tic = 0.0;
auto start = std::chrono::steady_clock::now();

tic = (float)start.count();

return tic;
}


Thank you!

Edit:

GetTime()
function should return current time to calculate delta time to frequently update objects in my program like:

fPastTime = fCurrentTime;
fCurrentTime = GetTime();

fDt = fCurrentTime - fPastTime;
if (fDt >= 0.15f)
fDt = 0.15f;
Update(fDt);

Answer

Recommendation:

std::chrono::steady_clock::time_point
GetTime()
{
    return std::chrono::steady_clock::now();
}

If you want the result of the timing in terms of float-based seconds, do this:

using fsec = std::chrono::duration<float>;
auto t0 = GetTime();
some_function();
auto t1 = GetTime();
fsec delta = t1 - t0;
std::cout << delta.count() << "s\n";
  • You are not responsible for any units conversions, therefore you will not introduce any bugs in this area.
  • The code is simple. Simple == low risk.
  • There is really not a need for the GetTime() wrapper.

Edit:

#include <chrono>

using namespace std::chrono;

using fsec = duration<float>;
using ftp = time_point<steady_clock, fsec>;

ftp
GetTime()
{
    return steady_clock::now();
}

int
main()
{
    auto fPastTime = GetTime();
    auto fCurrentTime = GetTime();

    auto fDt = fCurrentTime - fPastTime;
    if (fDt >= 0.15s)
        fDt = 0.15s;
    // ...
}

The 0.15s requires C++14. In C++11 that looks like:

    if (fDt >= fsec{0.15})
        fDt = fsec{0.15};
Comments