C++ 用C++计算执行时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/876901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:45:08  来源:igfitidea点击:

calculating execution time in c++

c++execution-time

提问by Hick

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.

我写了一个c++程序,我想知道如何计算执行所花费的时间,这样我就不会超过时间限制。

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

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

回答by Ashutosh Mehra

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

如果您安装了 cygwin,从它的 bash shell 运行您的可执行文件,例如MyProgram,使用该time实用程序,如下所示:

/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:

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

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

回答by Sajal

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

使用 C++11 来测量一段代码的执行时间,我们可以使用 now() 函数:

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 变量的值也可以截断为整数值,例如,如果您希望结果表示为:

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

For more info click here

欲了解更多信息,请单击此处

回答by Mathew Kurian

OVERVIEW

概述

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

我已经使用@AshutoshMehra响应为此编写了一个简单的语义黑客。这样你的代码看起来真的很可读!

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

回答by Alex Jenter

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.

注意:这个问题最初是关于编译时间的,但后来发现 OP 真的意味着执行时间。但也许这个答案对某人仍然有用。

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

对于 Visual Studio:转到Tools / Options / Projects and Solutions / VC++ Project Settings并将Build Timing选项设置为“ yes”。之后,每次构建的时间将显示在输出窗口中。

回答by pjc50

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.

这看起来像 Dijstra 的算法。在任何情况下,运行所需的时间将取决于 N。如果它花费的时间超过 3 秒,我看不出有任何方法可以加快速度,因为它正在执行的所有计算都需要完成。

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

根据您要解决的问题,可能有更快的算法。

回答by ejjyrex

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

我已经使用了上面提到的技术,但我仍然发现Code:Blocks IDE 中给出的时间与获得的结果或多或少相似-(可能会相差一点微秒)。