How can I make a C++ timer?:confused:

Recommended Answers

All 6 Replies

How good of a timer are you trying to write? If it's a boo-boo practice exercise or you don't need sub-second granularity, the standard <ctime> library is more than sufficient. Just wrap a few function calls in a class and call it good.

I just need something to count until a certain point then do something but I don't know how to.
I've used #include <ctime>, I don't know what functions it has though.

>I don't know what functions it has though.
Hmm, that sounds like a job for a reference. :icon_rolleyes:

Here's a quickie example to get you started:

#include <ctime>
#include <iostream>

namespace jsw {
    class timer {
        bool _running;
        time_t _start;
        time_t _stop;
        double _elapsed;
    public:
        timer() { start(); }

        void start()
        {
            _start = std::time(0);
            _running = true;
        }

        void stop()
        {
            _stop = std::time(0);
            _elapsed = std::difftime(_stop, _start);
            _running = false;
        }

        double elapsed() const
        {
            return _running ? std::difftime(std::time(0), _start) : _elapsed;
        }
    };
}

int main()
{
    std::cout<<"Stop! "<<std::flush;

    jsw::timer timer;

    while (timer.elapsed() <= 3)
        ;

    std::cout<<"Hammer time!\n";
}

How can I make that will count for 5 seconds and show the seconds go down.
(Start at 5.)

>How can I make that will count for 5 seconds and show the seconds go down.
I'm not here to do your thinking for you. Be thankful that I gave you an example instead of forcing you to figure it out on your own from the reference link.

Anyway, there are a number of ways to go about doing what you want. One simple way is to use the timer to pause between iterations of a loop:

int main()
{
    for (int i = 5; i > 0; i--) {
        std::cout<< i <<'\n';
        jsw::timer timer;
        while (timer.elapsed() < 1)
            ;
    }

    std::cout<<"Happy New Year!\n";
}

But if you're going to use the timer like that, I strongly recommend rehashing the interface to make it more user friendly. As written it's meant to be more of a poor man's profiler.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.