Perhaps a bit of simpler code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main()
{
int timer = 0;
while (true)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << (timer += 1) << '\n';
}
return 0;
}
| |
With this code, you keep track of seconds yourself.
However, your code isn't a timer at all - It's not at all keeping track of time.
The issue with your code is that you don't know when you're checking. By the time you make "timestored" equal time(NULL) and then check if time(NULL) has changed, a second hasn't passed! C++ is very fast, but your program is relying on a time difference great enough from line 12 to 13 that time(NULL) actually gets incremented to the next second in order to become different than "timestored".
To better explain, lets say it takes 50 milliseconds to assign timestored to time(NULL). Then, it takes another 50 milliseconds to evaluate the if statement. In that time, a single second hasn't even passed! The only time it prints out a number is when that small fraction of a second is all the time that was left in the current second before it passed, hence why it likely runs very differently every time you compile it. (Note that that's not actually how long it takes, but it was just for the example. Your code is being processed very quickly, at fractions of a second.)
Therefore, you can see that your program wasn't keeping track of time at all. Even if you could ensure that you check the condition in the next second, the program wouldn't be accurate about
when in the next second, you'd have a ridiculously large error margin.
EDIT: I hope that was understandable, let me know if you need it explained again.