problem with clock()

#include<iostream>
#include<time.h>
using namespace std;
int main()
{
    system("date");
    clock_t start = clock();
         int i=9*8;
         while(i--)
         {
             int j=9999999;
             while(j--);
         }
    clock_t end = clock();
    double elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
    cout<<"elapsed:"<<elapsed<<"\n";
    system("date");
}

system info :SunOS sundev2 5.9 Generic_Virtual sun4u sparc SUNW,Sun-Fire-V245
g++ (GCC) 3.4.6
It takes around 5 secs to execute,but clock returns 17 secs

$./a.out
Tue Jul 27 05:14:24 PDT 2010
elapsed:17.9997
Tue Jul 27 05:14:29 PDT 2010

Exact same box/OS I get (gcc 3.2.3):

> ./a.out
Tue Jul 27 07:34:36 MDT 2010
6.980000
Tue Jul 27 07:34:43 MDT 2010

Solaris 10 with gcc 3.4.3

# ./a.out
Tue Jul 27 07:43:59 MDT 2010
3.700000
Tue Jul 27 07:44:03 MDT 2010
#

It could be a C runtime problem, since Solaris 9 has been out for years, I would assume some patches are missing on your box. I stopped sysadmin with 8, just started back with 10, I missed 9 all together. Maybe another Solaris person knows what those patches are.

From the manpage:

       On several other implementations, the value returned  by  clock()  also
       includes  the times of any children whose status has been collected via
       wait(2) (or another wait-type call).  Linux does not include the  times
       of  waited-for children in the value returned by clock().  The times(2)
       function, which explicitly returns  (separate)  information  about  the
       caller and its children, may be preferable.

...so you may be corrupting your clock() call by running commands in system(), though it's still odd that it'd mung it that far. Try removing the system() calls and just printing the clock() values, running the program with 'time ./program' to see how your values compare to the ones time sees.

1 Like

Following Corona's thought:

time ./a.out

gives what output?

 
$cat ts.C
#include<iostream>
#include<time.h>
using namespace std;
int main()
{
clock_t start = clock();
int i=9*8;
while(i--)
{
int j=9999999;
while(j--);
}
clock_t end = clock();
cout<<"elapsed:"<<((end - start) / CLOCKS_PER_SEC)<<"\n";
}
$g++ ts.C
$time ./a.out
elapsed:17
real 0m4.364s
user 0m4.320s
sys 0m0.011s
$
 
 

Some patch should be missing
Thanks for the command 'time'