这个网站上已经存在很多性能问题,但是我发现几乎所有这些都是特定于问题且相当狭窄的问题.几乎所有人都重复这些建议,以避免过早优化.
我们假设:
我在这里寻找的是在一个关键算法中挤出最后几个百分点的策略和技巧,除此之外别无他法.
理想情况下,尝试使答案语言不可知,并在适用的情况下指出建议策略的任何缺点.
我将使用我自己的初步建议添加回复,并期待Stack Overflow社区可以想到的任何其他内容.
我一直认为这std::vector
是"作为阵列实施的一般智慧",等等等等等等.今天我去了测试它,似乎不是这样:
这是一些测试结果:
UseArray completed in 2.619 seconds
UseVector completed in 9.284 seconds
UseVectorPushBack completed in 14.669 seconds
The whole thing completed in 26.591 seconds
Run Code Online (Sandbox Code Playgroud)
这大约慢了3-4倍!没有真正证明" vector
可能会慢几纳米"的评论.
我使用的代码:
#include <cstdlib>
#include <vector>
#include <iostream>
#include <string>
#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/date_time/microsec_time_clock.hpp>
class TestTimer
{
public:
TestTimer(const std::string & name) : name(name),
start(boost::date_time::microsec_clock<boost::posix_time::ptime>::local_time())
{
}
~TestTimer()
{
using namespace std;
using namespace boost;
posix_time::ptime now(date_time::microsec_clock<posix_time::ptime>::local_time());
posix_time::time_duration d = now - start;
cout << name << " completed in " << …
Run Code Online (Sandbox Code Playgroud) 我最近发现这个名为codechef的网站,您可以在其中提交问题解决方案.我已经为一个问题提交了两个答案,一个在C中,另一个在C++中.两个代码几乎相同.但是当我在C中提交的代码在4.89s中执行时,我在C++中提交的代码超时(超过8秒).这怎么可能?时间到了哪里?
输入
输入以两个正整数nk(n,k <= 107)开始.接下来的n行输入包含一个正整数ti,每个整数不大于10 ^ 9.
产量
写一个整数来输出,表示有多少整数ti可以被k整除.
Example
Input:
7 3
1
51
966369
7
9
999996
11
Output:
4
Run Code Online (Sandbox Code Playgroud)
#include<stdio.h>
int main() {
int n,k,t;
scanf("%d %d",&n,&k);
int i,num=0;
for(i=0;i<n;i++) {
scanf("%d",&t);
if(t%k==0) num++;
}
printf("%d",num);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
#include<iostream>
using namespace std;
int main() {
int n, k, t,num=0;
cin>>n>>k;
for(int i=0;i<n;i++) {
cin>>t;
if(t%k==0) num++;
}
cout<<num;
return 0;
}
Run Code Online (Sandbox Code Playgroud)