Whats wrong with my code?

Apr 22, 2012 at 6:28am
I have written this simple code to measure the time duration it takes for a user to input the data for calculation. Please help me and correct this program. I shall stay thankful..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//To calculate time duration it takes to perform an operation of addition

#include <iostream>
#include <conio>
#include <time.h>
int main()
{
int a,b,c;
int start, finish;

clock_t start (clock());   //THIS LINE IS GIVING ME ERROR!!
cout<<"Enter digit";
cin>>a;
cout<<"\nEnter digit";
cin>>b;
c = a+b;
clock_t finish (clock()); //THIS LINE IS ALSO GIVING ME ERROR!!


cout<<"Time to calculate sum is:"<<(finish-start)/1000.0<< "seconds";
cout<<c;
getche();
}
Last edited on Apr 22, 2012 at 6:30am
Apr 22, 2012 at 6:33am
I haven't really worked with clock, but I'm guessing that your functions are value-returning, which means you need to set your variables equal to the function.

Ex:
start = clock_t(clock());

But this is just my guess. Error messages might help in getting your problem solved if this is not the case.
Apr 22, 2012 at 8:37am
No i checked with this too. It doesn't work! Can you suggest something else?? Please
Apr 22, 2012 at 9:25am
You can't have two variables named start and finished.
Apr 22, 2012 at 9:33am
What error are you getting??? You should always quote the error the compiler, linker, debugger, or program/system reports.

But I can see you are declaring int variables called start and finish and then reusing the same names to declare clock_t variables. Removing the line int start, finish; should fix the error (which I would think is a complaint about using the same varable names).

Or you can change line 9 to:
clock_t start, finish;

and then use

start = clock();

and

finish = clock();

Andy

PS GRex2595's suggestion is benign but unnecessary. clock() returns a value of type clock_t (clock ticks), and this line is just a cast to type clock_t (which it already is)

start = clock_t(clock());

same as

start = (clock_t)clock();
Last edited on Apr 22, 2012 at 9:42am
Apr 22, 2012 at 7:03pm
In my defense, I didn't realize that clock_t was a class. I thought that clock_t was a function which would lead me to believe that my line was the solution, but it's good to know that it's a class and I might be able to use this now.
Apr 22, 2012 at 7:49pm
clock_t isn't a class. It's just a typedef (like size_t) of some integral type (Digital Mars's C++ compiler uses a long), which is all that's needed to represent a tick count.
Last edited on Apr 22, 2012 at 7:52pm
Apr 23, 2012 at 12:13am
Ok. . .
Topic archived. No new replies allowed.