简体   繁体   中英

timer on counting the total time execution on a program for c++?

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?

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:

  • Undeclared j and seconds are used.
  • Multi-character character literals are used where I think string literals should be 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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM