我想比较使用Python和C++从stdin读取字符串的读取行,并且看到我的C++代码运行速度比等效的Python代码慢一个数量级,这让我很震惊.由于我的C++生锈了,我还不是专家Pythonista,请告诉我,如果我做错了什么或者我是否误解了什么.
(TLDR回答:包括声明:cin.sync_with_stdio(false)或者只是fgets改用.
TLDR结果:一直向下滚动到我的问题的底部并查看表格.)
C++代码:
#include <iostream>
#include <time.h>
using namespace std;
int main() {
string input_line;
long line_count = 0;
time_t start = time(NULL);
int sec;
int lps;
while (cin) {
getline(cin, input_line);
if (!cin.eof())
line_count++;
};
sec = (int) time(NULL) - start;
cerr << "Read " << line_count << " lines in " << sec << " seconds.";
if (sec > 0) {
lps = line_count / sec;
cerr << " LPS: " << lps …Run Code Online (Sandbox Code Playgroud) 我正在使用Windows7使用CPython for python3.22和MinGW的g ++.exe for C++(这意味着我使用libstdc ++作为运行时库).我写了两个简单的程序来比较它们的速度.
蟒蛇:
x=0
while x!=1000000:
x+=1
print(x)
Run Code Online (Sandbox Code Playgroud)
C++:
#include <iostream>
int main()
{
int x = 0;
while ( x != 1000000 )
{
x++;
std::cout << x << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
两者都没有优化.
我先运行c ++,然后通过交互式命令行运行python,这比直接启动.py文件慢得多.
但是,python outran c ++的速度是原来的两倍多.Python花了53秒,c ++花了1分54秒.
是因为python对解释器进行了一些特殊的优化,还是因为C++必须引用和std会降低它并使它占用ram?
还是其他原因?
编辑:我再次尝试,\n而不是std::endl,并用-O3旗帜编译,这次花了1分钟达到500,000.
我在Windows操作系统上启动这两个控制台应用程序.这是我的C#代码
int lineCount = 0;
StreamWriter writer = new StreamWriter("txt1.txt",true);
for (int i = 0; i < 900; i++)
{
for (int k = 0; k < 900; k++)
{
writer.WriteLine("This is a new line" + lineCount);
lineCount++;
}
}
writer.Close();
Console.WriteLine("Done!");
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
这是我的C代码.我假设它是C,因为我包括cstdio并使用标准fopen和fprintf功能.
FILE *file = fopen("text1.txt","a");
for (size_t i = 0; i < 900; i++)
{
for (size_t k = 0; k < 900; k++)
{
fprintf(file, "This is a line\n");
} …Run Code Online (Sandbox Code Playgroud)