1

This is my code:

double sec = 0;

while (1)
{
    sec += 0.01;
    Sleep(10);
    cout << sec << endl;
}

I want to make a stopwatch. I used the Sleep function to increase variable every 10ms, but output variable doesn't match with the computer's stopwatch.

  • Can you tell me a reason?
  • and is there any other way to make a stopwatch?
Melebius
  • 6,183
  • 4
  • 39
  • 52
SoulSystem
  • 51
  • 5
  • 2
    What is your platform? – Jabberwocky Jul 20 '20 at 08:51
  • 2
    no idea what Sleep is, but it might be that it waits at minimum the given time. The rest of the code also needs time. How to solve: Use a timer which calls your function periodical . – Klaus Jul 20 '20 at 08:53
  • Does this answer your question? [Getting wrong value for Millisecond delay](https://stackoverflow.com/questions/62445592/getting-wrong-value-for-millisecond-delay) – Nilesh Solanki Jul 20 '20 at 09:01
  • 4
    [Without a Minimal, Complete, Verifiable Example, it is hard to know what is wrong.](http://idownvotedbecau.se/nomcve/) Please [edit] your question to include a working program, e.g. by including the `#include`s used by your program. – Melebius Jul 20 '20 at 09:23
  • you have to use the sleep function properly.I have given complete sleep example solution in the link, [c++ sleep function guidelines][1] [1]: https://svsivan.blogspot.com/2020/07/sleep-function-c.html – shivcena Jul 20 '20 at 09:47
  • https://stackoverflow.com/questions/43051948/why-is-stdcout-so-time-consuming "Replace << std::endl; with << '\n'. This will refrain from flushing the internal buffer of the C++ runtime to the operating system on every single line. It should result in a huge performance improvement." – Nilesh Solanki Jul 20 '20 at 10:27
  • You want to query current time at the beginning and before each sleep, and calculate the delay based on that. If you want to print a message every 10 ms, then your wakeups are x+0, x+10, x+20, x+30... ms. If current time is x+11, then you only need to sleep 9ms. If it's x+25, you only need to sleep 5 ms. – n. m. could be an AI Jul 20 '20 at 10:38
  • @shivcena this will not work by exactly the same reason the original attempt doesn't work. – n. m. could be an AI Jul 20 '20 at 10:39
  • @NileshSolanki If you don't flush the buffer, you don't see messages as they are sent to the output. You only see them when the system decides to flush. What good is a stopwatch that beeps 10 seconds after it stops because its internal buffer was not full enough to flush? – n. m. could be an AI Jul 20 '20 at 10:41
  • You should also know that a typical Windows console probably cannot print a line each 10 ms. There is not enough oomphs to scroll the buffer that fast. You may want to print all output on the same line with `<< 'r' << std::flush` or something. – n. m. could be an AI Jul 20 '20 at 10:44

0 Answers0