4

Is there some specific number of iterations, that I could make using a for loop, so that it exactly takes 1 second for the loop to be executed completely? For example the following code took 0.125s on my machine to execute:

#include <iostream>
#include <cmath>

using namespace  std;

int main(){
    long long a=0;

    for (a=0;a<=pow(10,4);a++);
}

Though, a <= 8*pow(10,4) took 0.206 s. Compiler is GCC 4.9.2. IDE is codeblocks.

My PC's Specs: OS: Windows 8.1 enter image description here

anshabhi
  • 423
  • 6
  • 29
  • 1
    Probably not, because the compiler may optimize different code differently. – πάντα ῥεῖ Jun 14 '15 at 11:25
  • 1
    Sure. A busy-loop calling `clock()` over and over. But why would you want to do that? – Daniel Kamil Kozar Jun 14 '15 at 11:25
  • 2
    The time that an iteration will take is *unpredictable*, this can not work with just a for loop. Not only does this depend on the CPU used, but you need to take into account power management, the scheduler, etc. – tux3 Jun 14 '15 at 11:26
  • 8
    You'd have to use a real time OS to accomplish that. There's too much jitter in non realtime OSs. Windows could decide to schedule other processes for a while, or use the CPU for e.g. kernel networking, disk I/O etc. that preempts your timing. – nos Jun 14 '15 at 11:26
  • 4
    I don't see reasons to downvote. – edmz Jun 14 '15 at 11:27
  • @DanielKamilKozar just for fun, sometimes, I like experimenting! – anshabhi Jun 14 '15 at 11:29
  • 4
    You can't "make your own timer" in a hosted environment just in standard C++. A timer is essentially a mechanism to communicate with the OS scheduler, and you need platform-specific OS services for that. – Kerrek SB Jun 14 '15 at 11:39
  • Building on @πάνταῥεῖ's comment: as it is, your loop will be removed through dead code elimination. – Jongware Jun 14 '15 at 11:48

1 Answers1

0

I am posting this answer to your question, as per the comments received.

It is not possible to make a timer because:

  • The time that an iteration will take is unpredictable, this depends not only on the CPU used, but you need to take into account power management, the scheduler. (By tux3)
  • one would have to use a real time OS to accomplish that. There's too much jitter in non realtime OSs. Windows could decide to schedule other processes for a while, or use the CPU for e.g. kernel networking, disk I/O etc. that preempts the timing. (By nos)

  • One can't "make own timer" in a hosted environment just in standard C++. A timer is essentially a mechanism to communicate with the OS scheduler, and one needs platform-specific OS services for that. (By Kerrek SB)

  • The compiler would optimize such a loop and will remove it through dead-code elimination (By πάντα ῥεῖ and Jongware).

anshabhi
  • 423
  • 6
  • 29