我有两段 C++ 代码,它们执行相同的计算。与代码 A 相比,代码 B 确实减少了大约 33% 的指令,大约减少了 17% 的内存访问,但运行速度是代码 A 的四倍(而不是两倍)。会是什么原因呢?此外,我们如何才能确认您的回答所提供的主张?
在这两个代码中,
howmany是 20 000 000testees有 20 000 000 个元素,mt19937在启动时(在这些片段之前)为代码 A 和代码 B 随机生成 ( )。-O1代码 A - 运行时间约为。95 至 110 毫秒
GF2 sum {GF2(1)};
auto a = system_clock::now();
for(size_t i=0;i<howmany;i++){
sum *= testees[i];
}
auto b = system_clock::now();
Run Code Online (Sandbox Code Playgroud)
代码 B - 运行时间约为。25 至 30 毫秒
GF2 sum1 {GF2(1)};
GF2 sum2 {GF2(1)};
GF2 sum3 …Run Code Online (Sandbox Code Playgroud) 考虑以下代码:
int main(){
char hi[5] = "Hi!";
printf("%d", hi[4]);
}
Run Code Online (Sandbox Code Playgroud)
将打印什么?更重要的是,是否有什么会被印制的标准一提,在最新的 C ++标准?如果有提及,它在哪里?
由于某种原因,关于此的最新信息非常难以找到,并且各种来源的信息相互矛盾。我尝试过en.cppreference.com和cplusplus.com,前者没有任何信息,后者声称这些值不确定。然而,
using namespace std;
int main(){
char mySt[1000000] = "Hi!";
for(int i=0;i<1000000;++i){
if(mySt[i]!='\0') cout << i <<endl;
}
}
Run Code Online (Sandbox Code Playgroud)
这只会在我的系统上打印0、1和2,因此我希望将“ rest”初始化为“ \ 0”。据我所知char mySt[100000]=""初始化了整个数组'\0',并且说它与任何其他字符串文字都不同感到很尴尬。但是,如果我的讲师另有声明(他声称这是“未定义的”),则我需要用最新的具体证据(如有)来备份我的主张。
我在MinGW g ++ 8.2.0上编译。先感谢您。
澄清,
首先,举一个例子来说明我的问题背后的道德:下面的代码将无法编译,因为 std::basic_ostream::operator<< 是const不合格的。(https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-3.4/ostream-source.html显示操作符const不合格。)
我使用 GNU g++ 6.4.0 编译器编译,并启用了 --std=c++11 标志。
#ifndef TEST_H
#define TEST_H
#include<string>
#include<iostream>
using namespace std;
class ChessPiece{
const string name;
const int side;
public:
ChessPiece(const string&,const int);
void printPiece(const ostream&) const;
};
#endif // TEST_H
Run Code Online (Sandbox Code Playgroud)
...和test.cpp。
#include"test.h"
ChessPiece::ChessPiece(const string& s,const int bw): name{s}, side{bw} {}
void ChessPiece::printPiece(const ostream& S=cout) const{
S << "a " << (side==1?"white ":"black ") << name << endl;
}
int main(){
ChessPiece p{string("pawn"),-1}; // a black …Run Code Online (Sandbox Code Playgroud)