M
M
Maxim Ivanov2014-10-12 20:37:43
C++ / C#
Maxim Ivanov, 2014-10-12 20:37:43

How to check the speed of code execution in C++?

#include <iostream>
using namespace std;

int main()
{

 int n = 12;
 int a[n];

 a[0]=-1;
 a[1]=5;
 a[2]=4;
 a[3]=6;
 a[4]=0;
 a[5]=9;
 a[6]=7;
 a[7]=10;
 a[8]=-5;
 a[9]=23;
 a[10]=-9;
 a[11]=1;

int i = 0;
int j = 0;
int buffer = 0;

for(i=0; i<n; ++i){
    for (j=0;j<(n-1-i); ++j){
      if (a[j]>a[j+1]) {
          buffer = a[j+1];
          a[j+1] = a[j];
          a[j] = buffer;
       }
    }
}

 for (i=0; i<n; ++i) {
     cout<<a[i]<<endl;
 }



 system("pause");
 return 0;
}

How to check the speed of the main() function? in micro (nano) seconds?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
cjey, 2014-10-13
@omaxphp

#include <iostream>
#include <cstdio>
#include <ctime>

int main() {
    std::clock_t start;
    double duration;

    start = std::clock();

    /* Сюда вставить тестируемый код */

    duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;

    std::cout<<"printf: "<< duration <<'\n';
}

If the value is too small, then you can repeat the code being tested 1000 times and divide the total time by 1000.
In general, you need to increase the value of N to at least 10000, and fill the array with random values ​​in a loop.

S
smanioso, 2014-10-12
@smanioso

One might assume O(1) for an optimizing compiler.

K
Kyberman, 2014-10-13
@Kyberman

If on Linux, then you can use the time command.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question