题
我已经写了一个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;
}
这是我的程序,我希望它是时间限制在3秒内!!怎么做 ? 耶抱歉,我的意思执行时间!!
解决方案
如果您已经安装了cygwin,从它的bash shell中运行可执行文件,说MyProgram
,使用time
工具,就像这样:
/usr/bin/time ./MyProgram
这将报告程序的执行花了多长时间 - 输出将类似于以下内容:
real 0m0.792s
user 0m0.046s
sys 0m0.218s
您也可以手动修改你的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;
}
其他提示
使用下测量一段代码的执行时间++ 11,我们可以使用现在()函数:
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;
如果您想打印在上面的代码开始和结束之间的时间差,你可以使用:
cout << chrono::duration <double, milli> (diff).count() << " ms" << endl;
如果你喜欢使用纳秒,您将使用:
cout << chrono::duration <double, nano> (diff).count() << " ns" << endl;
的DIFF变量的值也可以被截断为一个整数值,例如,如果你想要的结果表示为:
diff_sec = chrono::duration_cast<chrono::nanoseconds>(diff);
cout << diff_sec.count() << endl;
有关更多信息请点击这里
<强>概览强>
我写此使用@AshutoshMehra
response一个简单的语义黑客攻击。你的代码看起来非常可读的这种方式!
<强> 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
}
<强>输出强>
Block Speed: 0.127000000s
请注意:这个问题本来约编译时间,但后来事实证明,在OP真正含义执行时间。但是,也许这个答案仍然是有用的人。
对于Visual Studio:去Tools / Options / Projects and Solutions / VC++ Project Settings
并设置Build Timing
选项 'yes
'。后,每一个构建的时间将显示在输出窗口。
这看起来像Dijstra算法。在任何情况下,运行所花费的时间将取决于N.如果花费的时间超过3秒没有任何方法可以让我看到飞驰起来的,因为所有的计算,这是做需要做的工作。
根据你想解决什么问题,有可能是一个更快的算法。
我已经使用的技术中上面所说的,还是我发现,在代码给出的时间:块IDE 强>或多或少类似于结果obtained-(可能是它会一点一点不同微秒)..