1

I wonder how can I wait exactly one second using a special function called WastedTime which takes one argument MaxDelay and inside the method it does some weird calculations causing the program to waste time with calculations. I want to waste exactly one second. After a lot of attempts, 360,000,00 seems to work. But how can I validate that the program sleep for one second?

More body performance in a loop will waste more computation time - resulting in a delay between prints. Write the full method that accepts the MaxDelay value as a parameter and place it in the main program call it that way Let the clock print a line every second. Check what is the most appropriate value for MaxDelay to run the watch accurately. Try running for a minute And compare to a real watch.

For now it seems like it actually wait one second but I wonder how can I make sure it does?

using System;

class Program
{
    static void Main(string[] args)
    {
        const int MaxDelay = 36000000; // (360,000,00)
        for (int h = 0; h < 24; h++)
            for (int m = 0; m < 60; m++)
                for (int s = 0; s < 60; s++)
                {
                    WasteTime(MaxDelay);
                    Console.WriteLine(h + ":" + m + ":" + s);
                }
    }
    static void WasteTime(int MaxDelay)
    {
        double temp = 0;
        for (int delay = 1; delay <= MaxDelay; delay++)
            temp = Math.Pow(Math.PI, 2);
    }
}

Expected Output

0:0:0
// .. one second
0:0:1
// .. second
0:0:2

Note: Please leave the WasteTime as is

  • 4
    Why do you want to do this rather than simply using `Thread.Sleep(timeInMilliseconds);` (or `await Task.Delay(delay);` in async/await contexts)? – ProgrammingLlama Feb 10 '21 at 09:52
  • 3
    *"After a lot of attempts, 360,000,00 seems to work"* Now try it on a slower and a faster processor – Cid Feb 10 '21 at 09:52
  • 3
    The delays using busy loops is the reason why old games doesn't work on a new PCs, because they become unplayable fast. *"Please leave the WasteTime as is"* - why is that? Do you have a good argument against refactoring your clearly *wrong* approach? – Sinatr Feb 10 '21 at 09:56
  • @Sinatr it reminds me the very first GTA with the option "Frame Limiter" – Cid Feb 10 '21 at 09:59
  • @Cid, didn't played it, but I recall there were tools to slow down PC. Perhaps OP can also use one? – Sinatr Feb 10 '21 at 10:01
  • Nah I don't know guys. My teacher want us to play with the time and after a lot of attempts I still cannot solve it. What I need to do is to waste exactly one second. Isn't it hard? Nothing wrong with asking for help after a lot of unsuccessful attempts – zer0-padding Feb 10 '21 at 10:10
  • I've added the instructions of the task, hopefully it will help us solve the problem – zer0-padding Feb 10 '21 at 10:15
  • The teacher doesn't want _exactly_ one second. It is an exercise. Try and get it _close_ to one second. – mjwills Feb 10 '21 at 10:15
  • @mjwills Yeah maybe, I tried running it for a minute and compare it to a real watch and seems like it is very close. Will he accept it? – zer0-padding Feb 10 '21 at 10:16
  • That feels like a question for the teacher. How are they going to mark you wrong since the program will be different _on every PC_? – mjwills Feb 10 '21 at 10:16
  • @mjwills I have no clue, do you think our teacher know that it is depends on the machine itself? – zer0-padding Feb 10 '21 at 10:18
  • If it was me, what I would do is call the function and track how long it took and then adjust the parameter for future invocations (i.e. change the `MaxDelay` parameter). But a) I doubt that is what the teacher wants b) it doesn't factor in the non-zero cost of writing to the console. – mjwills Feb 10 '21 at 10:19
  • 5
    `do you think our teacher know that it is hardly depends on the machine itself?` If not, get a new teacher. – mjwills Feb 10 '21 at 10:19
  • @zer0-padding did you read the very first comment of John? – Cid Feb 10 '21 at 10:22
  • @Cid Yes, but as I said, the purpose is just to play with time. I thought about that but it is not what the teacher wants. I'd like to do that in the way John suggested – zer0-padding Feb 10 '21 at 10:23

2 Answers2

0

If you want to waste some exact time on a machine, your code has to perform a measurement how many times can something simple be computed in a smaller time, then upscale to the desired time and check if this matches.

So here is some sketch:

  • What time is it now?
  • Call your WasteTime() 1 thousans times
  • What time is it now?
  • How many time elapsed from the above given dates?
  • If e.g. it took 37 msec to perfom that task, note this timespan into a variable
  • If you like to wait 5 secs, divide this wait time with your single execution timespan.
  • Execute your simple task this many times.

Be aware that your numbers will always change, depending on the used computer, but also if you run a debug or release version. Depending on your simple task, the compiler could see, that you do nothing and optimize your code away.

Oliver
  • 43,366
  • 8
  • 94
  • 151
0

You would need to time how long one loop takes, for this you should use a stopwatch since this is the way to accurately measure time:

        WasteTime(1); // Warmup, ensure the method is compiled
        int timingLoopCount = 100000000;
        var sw = Stopwatch.StartNew();
        WasteTime(100000000); // Time some long loop
        sw.Stop();
        var loopsPerSecond = timingLoopCount * TimeSpan.TicksPerSecond / sw.Elapsed.Ticks;
        Console.WriteLine("Loops Per Second: " + loopsPerSecond);

You should never do this!

Since the WasteTime function does not return any result and have no side effects, the jitter could decide to just omit the function call, causing infinite/undefined number of loops per second. There are many other issues with such approach, like drift caused by varying load or power budget on the system.

This was somewhat common on older systems. On startup the system would loop some fixed amount of times and check how long it took. This became a common source of issues when computers got fast enough to complete all the loops faster than the resolution of the timer.

What you should use is:

  • DateTime for showing the system time
  • Stopwatch to measure time intervals with high precision
  • Timer for reoccurring events, like updating a clock.
  • Media timer for high precission reoccuring events (like video playback)
JonasH
  • 28,608
  • 2
  • 10
  • 23