Why is my timer not working?

closed account (SEw0ko23)
Hi, I have been making a maze based game over the past few weeks and i wanted to implement a timer into the game level, so the player can keep track of how long it took them to complete the game. I have managed to write some code for the timer, but i am unable to build and compile it and it does not output the time when i put it into my maze game code.
Here is the code:

#include <iostream.h>
#include <time.h>


class timer {
private:
unsigned long begTime;
public:
void start() {
begTime = clock();
}

unsigned long elapsedTime() {
return ((unsigned long) clock() - begTime) / CLOCKS_PER_SEC;
}

bool isTimeout(unsigned long seconds) {
return seconds >= elapsedTime();
}
};


void main() {
unsigned long seconds = 10;
timer t;
t.start();
cout << "timer started . . ." << endl;
while(true) {
if(t.elapsedTime() >= seconds) {
break;
}
else {
// do other things
}
}
cout << seconds << " seconds elapsed" << endl;

cin >> seconds; // it's just to stop the execution and look at the output
}

Thanks fot the help, and sorry that i dont know how to add my code as a code format on this forum
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <chrono>

struct timer
{
    void reset() { start = std::chrono::steady_clock::now() ; }

    unsigned long long milliseconds_elapsed() const
    {
        const auto now = clock::now() ;
        using namespace std::chrono ;
        return duration_cast<milliseconds>(now-start).count() ;
    }

    using clock = std::chrono::steady_clock ;
    clock::time_point start = clock::now() ;
};

int main()
{
    timer t ;

    std::cout << "press enter: " ;
    std::cin.get() ;

    std::cout << "elapsed milliseconds: " << t.milliseconds_elapsed() << '\n' ;
}

http://coliru.stacked-crooked.com/a/074d5dacae264ea3
Topic archived. No new replies allowed.