I fixed a few things in your code and added proper usage of std::chrono
. The changes list include:
- I removed all
(void)
arguments from function calls because it is just not so C++ way :-)
- I also removed
return 0;
from main()
that is not needed in C++ because compiler will put it for you.
- I typedef'ed a clock because it may be really hard to find a quality clock in current implementations right now. See my answer here. Basically right now you may want to use your custom clock and thanks to
typedef
refactoring may be easier in the future.
- I changed your wait loop to a C++11 sleep interface (you can randomise some duration there if you want - also with C++11 :-) ). That change was not need in that case but it nicely shows how
std::chrono
is also used in threading library.
- I put your methods implementations inside a class to give compiler a chance to inline them. Alternatively you could use
inline
keyword explicity in implementation outside of the class.
- I made your
time_elapsed()
method const
- I removed unnecesary
const
from a return value of time_elapsed()
method and added it on the other hand in usage of that method because in that exact place const
is enough.
- Last but not least, I modified your
time_elapsed()
method to return clock's native resolution in return
. It is much better solution because you never loose data here. You may want to loose it when providing the data to user in a specific unit (ie. us). You have to use duration_cast
there to tell the compiler that you agree on loosing some data and us resolution is enough for you.
I hope below code and above changes will be interesting to you.
#include <chrono>
#include <thread>
#include <iostream>
using namespace std::chrono;
class Timer {
public:
typedef high_resolution_clock Clock;
void start()
{ epoch = Clock::now(); }
Clock::duration time_elapsed() const
{ return Clock::now() - epoch; }
private:
Clock::time_point epoch;
};
int main() {
Timer timer;
timer.start();
// sleep some time
std::this_thread::sleep_for(microseconds(40));
const auto elapsed = timer.time_elapsed();
std::cout << duration_cast<microseconds>(elapsed).count() << "us" << std::endl;
}
BTW, I didn't want to play with the class interface (I already did too many changes). If you are not bound to that interface yet I recommend following one that @sehe suggested. But do not use that double
as a return value ;-)