我想比较使用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.
我知道C++应该比Python 3快得多,因为它是一种编译语言而不是解释语言.
我编写了两个程序,使用蒙特卡罗模拟来计算Pi,一个在Python 3中,另一个在C++中.
Python的结果比C++快大约16倍.如下图所示,重复值为(10,000,000),Python需要8.5秒,而C++需要137.4秒.
我是C++的新手,但我找不到解释这种行为的在线帖子.
根据这篇文章, C++一般应该比Python快10倍 - 100倍,这显然不是我的情况.
请帮助我理解为什么Python在我的情况下比C++快得多.
我的结果:
Python源代码:
from random import random
import time
import sys
class MonteCarloSimulator(object):
def __init__(self, value):
self.value = value
if sys.platform == "win32":
self.G = ''
self.R = ''
self.END = ''
else:
self.G = '\033[92m'
self.R = '\033[1;31m'
self.END = '\033[0m'
def unit_circle(self, x, y):
if (x ** 2 + y ** 2) <= 1:
return True
else: …Run Code Online (Sandbox Code Playgroud) c++ ×3
python ×3
benchmarking ×1
getline ×1
iostream ×1
montecarlo ×1
performance ×1
simulation ×1