54

I have written a c++ program , I want to know how to calculate the time taken for execution so I won't exceed the time limit.

#include<iostream>

using namespace std;

int main ()
{
    int st[10000],d[10000],p[10000],n,k,km,r,t,ym[10000];
    k=0;
    km=0;
    r=0;
    scanf("%d",&t);
    for(int y=0;y<t;y++)
    {
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
            cin>>st[i] >>d[i] >>p[i];
    }
    for(int i=0;i<n;i++)
    {
            for(int j=i+1;j<n;j++)
            {
                    if((d[i]+st[i])<=st[j])
                    {
                              k=p[i]+p[j];
                    }
                    if(k>km)
                    km=k;
            }
        if(km>r)
        r=km;
    }
    ym[y]=r;
}
    for( int i=0;i<t;i++)
    {
         cout<<ym[i]<<endl;
    }


    //system("pause");
    return 0;
}     

this is my program and i want it to be within time limit 3 sec !! how to do it ? yeah sorry i meant execution time !!

B Faley
  • 17,120
  • 43
  • 133
  • 223
Hick
  • 35,524
  • 46
  • 151
  • 243
  • 1
    What time limit? Only you can impose a time limit, and I can't think of a good reason for doing so. – duffymo May 18 '09 at 09:49
  • It's highly dependent on compiler/server/disk/other load. You generally never need such limit. – Drakosha May 18 '09 at 09:52
  • 2
    Are you sure you need to measure compilation time? Maybe you meant the execution time? – Alex Jenter May 18 '09 at 10:14
  • 7
    @mekasperasky: You should always fix all the parts of your question that are wrong. Don't simply add a little edit at the end. Fix the title, fix all the other places where it says "compilation". – S.Lott May 18 '09 at 10:37

9 Answers9

132

If you have cygwin installed, from it's bash shell, run your executable, say MyProgram, using the time utility, like so:

/usr/bin/time ./MyProgram

This will report how long the execution of your program took -- the output would look something like the following:

real    0m0.792s
user    0m0.046s
sys     0m0.218s

You could also manually modify your C program to instrument it using the clock() library function, like so:

#include <time.h>
int main(void) {
    clock_t tStart = clock();
    /* Do your stuff here */
    printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
    return 0;
}
Ashutosh Mehra
  • 2,582
  • 1
  • 19
  • 15
  • 16
    Note that clock() gets overall execution time. So if you use it with multithreaded code, you might get a result bigger, than you expect. – FreeNickname Aug 31 '13 at 13:56
  • Thanks FreeNickname, I was wondering why when I scaled up the threads my program ran more slowly! – Frederik Oct 08 '13 at 09:53
  • @Ashutosh Mehra, I am getting always zero as out put, with your clock code. what to do? – uss May 22 '14 at 14:51
51

With C++11 for measuring the execution time of a piece of code, we can use the now() function:

auto start = chrono::steady_clock::now();

//  Insert the code that will be timed

auto end = chrono::steady_clock::now();

// Store the time difference between start and end
auto diff = end - start;

If you want to print the time difference between start and end in the above code, you could use:

cout << chrono::duration <double, milli> (diff).count() << " ms" << endl;

If you prefer to use nanoseconds, you will use:

cout << chrono::duration <double, nano> (diff).count() << " ns" << endl;

The value of the diff variable can be also truncated to an integer value, for example, if you want the result expressed as:

diff_sec = chrono::duration_cast<chrono::nanoseconds>(diff);
cout << diff_sec.count() << endl;

For more info click here

Sajal
  • 1,783
  • 1
  • 17
  • 21
20

OVERVIEW

I have written a simple semantic hack for this using @AshutoshMehraresponse. You code looks really readable this way!

MACRO

#include <time.h>

#ifndef SYSOUT_F
#define SYSOUT_F(f, ...)      _RPT1( 0, f, __VA_ARGS__ ) // For Visual studio
#endif

#ifndef speedtest__             
#define speedtest__(data)   for (long blockTime = NULL; (blockTime == NULL ? (blockTime = clock()) != NULL : false); SYSOUT_F(data "%.9fs", (double) (clock() - blockTime) / CLOCKS_PER_SEC))
#endif

USAGE

speedtest__("Block Speed: ")
{
    // The code goes here
}

OUTPUT

Block Speed: 0.127000000s
Mathew Kurian
  • 5,949
  • 5
  • 46
  • 73
10

Note: the question was originally about compilation time, but later it turned out that the OP really meant execution time. But maybe this answer will still be useful for someone.

For Visual Studio: go to Tools / Options / Projects and Solutions / VC++ Project Settings and set Build Timing option to 'yes'. After that the time of every build will be displayed in the Output window.

Alex Jenter
  • 4,324
  • 4
  • 36
  • 61
6

You can try below code for c++:

#include <chrono>


auto start = std::chrono::system_clock::now();
// Your Code to Execute //
auto end = std::chrono::system_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl;
KRG
  • 655
  • 7
  • 18
3

This looks like Dijstra's algorithm. In any case, the time taken to run will depend on N. If it takes more than 3 seconds there isn't any way I can see of speeding it up, as all the calculations that it is doing need to be done.

Depending on what problem you're trying to solve, there might be a faster algorithm.

pjc50
  • 1,856
  • 16
  • 18
0

I have used the technique said above, still I found that the time given in the Code:Blocks IDE was more or less similar to the result obtained-(may be it will differ by little micro seconds)..

ejjyrex
  • 1,151
  • 1
  • 10
  • 13
0

If you are using C++ then you should try this below code as you would always get 0 as answer if you directly use @Ashutosh Mehra's answer.

#include <iostream>
#include <time.h>

using namespace std;

int main() {
    int a = 20000, sum=0;
    
    clock_t start = clock();
    for (int i=0; i<a; i++) {
        for (int k = 0; k<a; k++)
            sum += 1;
    }
    cout.precision(10);
    cout << fixed <<  float(clock() - start)/CLOCKS_PER_SEC  << endl;
    return 0;
}

Because in C++ you the float and double values will directly be rounded off. So I used the cout.precision(10) to set the output precision of any value to 10 digits after decimal.

greybeard
  • 2,249
  • 8
  • 30
  • 66
  • (Note that a half decent compiler would have to be prevented from generating no code at all for the nested loops - one possible explanation for [the problem sree mentions](https://stackoverflow.com/questions/876901/calculating-execution-time-in-c/68144498#comment36627392_876970). This could be impeded by `<< " for " << sum` before `<< endl`. Not sure about static evaluation …) – greybeard Jun 26 '21 at 20:06
0

shorter version of Ashutosh Mehra's answer:

/* including stuff here */
#include <time.h>
int main(void) {
    clock_t tStart = clock();
    /* stuff here */
    cout<<"Time taken: "<<(double)(clock() - tStart)/CLOCKS_PER_SEC;
    return 0;
}
Bang1338
  • 11
  • 4