2

The program listed below outputs 0 on the screen. Why? Does it mean that my computer is fast or something is wrong in the code?

#include <iostream>
#include <cstdio>
#include <ctime>
using namespace std;

int main(){
    int j=0;
    clock_t start=clock();
     for (int i=0;i<22220;i++){
         i++;
         j++;
         j+=i;
        // sleep(10);
     }

     clock_t final=clock()-start;
     cout<<final/ (double) CLOCKS_PER_SEC<<endl;

     return 0;
}
3
  • 1
    why are you doing i++ in the for-loop iterator section and in the body? and why j++ and j+=i? Commented Jul 10, 2010 at 20:23
  • and have you tried printing out just start and final to see what they show? Commented Jul 10, 2010 at 20:24
  • it just i want to take some time to execute these statements Commented Jul 10, 2010 at 20:41

3 Answers 3

3

Not sure about this, you might want to examine the outputted assembly code, but since neither i nor j are actually used in the rest of the program, the compiler might not generate any code for those instructions.

Sign up to request clarification or add additional context in comments.

Comments

2

Note that clock() doesn't return wall clock time, instead it has to do with the processing time in which sleep does nothing practically(it yields control to the operating system).

Try to remove sleep, and increase the loop count.

Comments

0
#include <windows.h>

SYSTEMTIME startTime;
GetSystemTime(&startTime);
WORD startmillis = (startTime.wSecond * 1000) + startTime.wMilliseconds;

// Do some stuff

SYSTEMTIME endTime;
GetSystemTime(&endTime);
WORD endmillis = (endTime.wSecond * 1000) + endTime.wMilliseconds;

WORD millis = startmillis - endmillis ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.