在c ++中计算执行时间 [英] calculating execution time in c++

查看:237
本文介绍了在c ++中计算执行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个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;
}

这是我的程序,我希望它在时间限制内3秒! !怎么做 ?
对不起,我的意思是执行时间!!

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

推荐答案

如果你安装了cygwin,可执行文件,例如 MyProgram ,使用时间实用程序,如下所示:

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

修改您的C程序以使用 clock()库函数对其进行检测,如下所示:

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;
}

这篇关于在c ++中计算执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆