Skip to content

Commit

Permalink
Use only std::chrono to calculate time.
Browse files Browse the repository at this point in the history
  • Loading branch information
PerMalmberg committed Nov 5, 2018
1 parent e8b3b90 commit 62e34af
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 22 deletions.
20 changes: 8 additions & 12 deletions lib/smooth/core/timer/ElapsedTime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

#include <smooth/core/timer/ElapsedTime.h>

using namespace std::chrono;

namespace smooth
{
namespace core
Expand All @@ -15,30 +17,24 @@ namespace smooth
if (active)
{
// Calculate new elapsed time
gettimeofday(&end_time, nullptr);
timersub(&end_time, &start_time, &elapsed);
end_time = std::chrono::steady_clock::now();
elapsed = end_time - start_time;
}

std::chrono::microseconds us(elapsed.tv_usec);
us += std::chrono::seconds(elapsed.tv_sec);
return us;
return duration_cast<microseconds>(elapsed);
}

std::chrono::microseconds ElapsedTime::get_running_time() const
{
timeval local_end_time;
timeval local_elapsed;
steady_clock::duration local_elapsed{};

if (active)
{
// Calculate new elapsed time
gettimeofday(&local_end_time, nullptr);
timersub(&local_end_time, &start_time, &local_elapsed);
local_elapsed = steady_clock::now() - start_time;
}

std::chrono::microseconds us(local_elapsed.tv_usec);
us += std::chrono::seconds(local_elapsed.tv_sec);
return us;
return duration_cast<microseconds>(local_elapsed);
}
}
}
Expand Down
16 changes: 6 additions & 10 deletions lib/smooth/include/smooth/core/timer/ElapsedTime.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

#pragma once

#include <ctime>
#include <sys/time.h>
#include <chrono>

namespace smooth
Expand All @@ -28,9 +26,9 @@ namespace smooth
/// Stops the performance timer
void stop()
{
gettimeofday(&end_time, nullptr);
end_time = std::chrono::steady_clock::now();
active = false;
timersub(&end_time, &start_time, &elapsed);
elapsed = end_time - start_time;
}

/// Functionally the same as start(), but provided for syntactical reasons.
Expand All @@ -43,7 +41,7 @@ namespace smooth
/// Zeroes the time, but lets it keep running.
void zero()
{
gettimeofday(&start_time, nullptr);
start_time = std::chrono::steady_clock::now();
end_time = start_time;
}

Expand All @@ -65,11 +63,9 @@ namespace smooth
}
private:
bool active = false;
timeval start_time{};
// Keep end_time as a member to get slightly more accurate values
// since it doesn't need to be constructed on the stack.
timeval end_time{};
timeval elapsed{};
std::chrono::steady_clock::time_point start_time{};
std::chrono::steady_clock::time_point end_time{};
std::chrono::steady_clock::duration elapsed{};
};
}
}
Expand Down

0 comments on commit 62e34af

Please sign in to comment.