为什么python打败了c++;在循环中?
以下是我的c++代码:为什么python打败了c++;在循环中?,python,c++,Python,C++,以下是我的c++代码: #include <iostream> #include <cstdio> #include <ctime> using namespace std; int main() { clock_t end; clock_t start = clock(); for(int i = 0; i < 1000; i++) { cout << "Test" << endl;
#include <iostream>
#include <cstdio>
#include <ctime>
using namespace std;
int main() {
clock_t end;
clock_t start = clock();
for(int i = 0; i < 1000; i++) {
cout << "Test" << endl;
}
end = clock() - start;
double duration = end / (double) CLOCKS_PER_SEC;
cout << "Duration: " << duration << endl;
getchar();
return 0;
} // This takes around ~ .9 secs on average
为什么PYTHON在这种情况下更快?我不确定这是否是因为我写了额外的代码,但这似乎是一个非常基本的for循环 > < <代码>循环>不是<代码>,但C++ >代码> IoStave。这并不是说
iostreams
的速度非常慢,而是你在为每一行做endl
C++不仅仅是'\n'
的同义词,它是一个io操纵器对象,当插入到流中时,插入'\n'
,然后请求刷新流。冲洗标准液可能非常缓慢
另一方面,Python不会刷新,除非您明确要求它刷新;否则,它只写入<代码> sys .STDUD/<代码>,这是一个 cout << "Test\n";
print("Test")
cout不是循环,而是循环中的内容。请使用static const char text[]=“Test\n”重试代码>…,可写(text,sizeof(text)-1)最大的潜在违规者是:在调试模式下编译而不进行优化和std::cout。使用FPET并确保您用-O2和没有-dYebug进行编译。我刚刚在我的机器上执行了代码(未修改),我得到的时间是:“代码> C++,带有Endl:0.001654,C++没有NeDL:0.001555,Python 3没有刷新:0.00 38 66 910934 448 242,Python 3与FLUH:0.00 51279067 99 316166 < /代码>。@ AbnNeT编译器:苹果LLVM版本91.0(clang-902.0.39.2),flags:-O3.stdlib:libc++iostreams的具体操作取决于实现。Microsoft对std::cout
的实现没有缓冲。它将使用fputc
@AlexeyB将字符逐个写入底层文件:与
同步是不受缓冲的。调用std::ios_base::sync_with_stdio(false)
它应该被缓冲。虽然刷新每一行是错误的,但错误计时的最可能原因实际上是没有优化代码。
cout << "Test\n";
print("Test")
cout << "Test" << endl;
print("Test", flush=True)