Reputation: 315
So I have this following simple program that I would like to have a timer imprinted in the program to count the exact time it takes for the program to execute on the number of n times.
for (int i=0; i<n; i++){
for (int j=1; j>=i; j++){
cout << "perfecto" << endl;
I was thinking of using the ctime library to help me out with the timer.
#include <iostream>
#include <ctime>
using namespace std;
time_t time_1;
time_t time_2;
time ( &time_1);
int main(){
int n=5;
for (int i=0; i<n; i++){
for (j=0; j<=i; j++){
cout << 'test';
}
}
}
time (&time_2 );
cout<<'time taken for the algorithm :'<<time_2 - time_1 << seconds <<endl;
Will this work somehow because when I ran this it shows me an error just like this.
Is there any other way to do it and is it possible to add a timer when starting the program?
Upvotes: 1
Views: 57
Reputation: 75062
Statements to be executed have to be inside function bodies.
#include <iostream>
#include <ctime>
using namespace std;
int main(){ // move here
time_t time_1;
time_t time_2;
time ( &time_1);
// move this above
//int main(){
int n=5;
for (int i=0; i<n; i++){
for (j=0; j<=i; j++){
cout << 'test';
}
}
// move this below
//}
time (&time_2 );
cout<<'time taken for the algorithm :'<<time_2 - time_1 << seconds <<endl;
} // move here
Also there are some more errors:
j
and seconds
are used.Do you mean this?
#include <iostream>
#include <ctime>
using namespace std;
int main(){
time_t time_1;
time_t time_2;
time ( &time_1);
int n=5;
for (int i=0; i<n; i++){
for (int j=0; j<=i; j++){
cout << "test";
}
}
time (&time_2 );
cout<<"time taken for the algorithm :"<<time_2 - time_1 << "seconds" <<endl;
}
Upvotes: 3