我在2009年首先注意到GCC(至少在我的项目和我的机器上)如果我优化尺寸(-Os)而不是速度(-O2或-O3),则会产生明显更快的代码,我一直想知道为什么.
我设法创建(相当愚蠢)代码,显示这种令人惊讶的行为,并且足够小,无法在此处发布.
const int LOOP_BOUND = 200000000;
__attribute__((noinline))
static int add(const int& x, const int& y) {
return x + y;
}
__attribute__((noinline))
static int work(int xval, int yval) {
int sum(0);
for (int i=0; i<LOOP_BOUND; ++i) {
int x(xval+sum);
int y(yval+sum);
int z = add(x, y);
sum += z;
}
return sum;
}
int main(int , char* argv[]) {
int result = work(*argv[1], *argv[2]);
return result;
}
Run Code Online (Sandbox Code Playgroud)
如果我用-Os它编译它,执行这个程序需要0.38秒,如果用-O2 …
我正在编写一个程序,直接从用户输入读取数据,并想知道我怎么能(没有循环)读取所有数据,直到标准输入EOF.我正在考虑使用,cin.get( input, '\0' )但'\0'不是真正的EOF角色,只读到EOF或者'\0'以先到者为准.
或者使用循环是唯一的方法吗?如果是这样,最好的方法是什么?
我在这里阅读了一个答案,展示了如何使用以下一(2)个内容将整个流读入std :: string:
std::istreambuf_iterator<char> eos;
std::string s(std::istreambuf_iterator<char>(stream), eos);
Run Code Online (Sandbox Code Playgroud)
对于做类似的读取一个二进制流成的东西std::vector,为什么我不能简单地替换char用uint8_t和std::string用std::vector?
auto stream = std::ifstream(path, std::ios::in | std::ios::binary);
auto eos = std::istreambuf_iterator<uint8_t>();
auto buffer = std::vector<uint8_t>(std::istreambuf_iterator<uint8_t>(stream), eos);
Run Code Online (Sandbox Code Playgroud)
以上产生编译器错误(VC2013):
1> d:\non-svn\c ++\library\i\file\filereader.cpp(62):错误C2440:'':无法从'std :: basic_ifstream>'转换为'std :: istreambuf_iterator>'1>
with 1> [1> _Elem = uint8_t 1>] 1>
没有构造函数可以采用源类型,或者构造函数重载解析是模糊的