Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

calculating execution time in c++

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 !!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
", (double)(clock() - tStart)/CLOCKS_PER_SEC);
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...