c+和python哪个快-Python比C ++快?这是怎么回事?

1586010002-jmsa.png

I'm using Windows7 using CPython for python3.22 and MinGW's g++.exe for C++ (which means I use the libstdc++ as the runtime library). I wrote two simple programs to compare their speed.

Python:

x=0

while x!=1000000:

x+=1

print(x)

C++:

#include

int main()

{

int x = 0;

while ( x != 1000000 )

{

x++;

std::cout << x << std::endl;

}

return 0;

}

Both not optimized.

I ran c++ first, then i ran python through the interactive command line, which is much slower than directly starting a .py file.

However, python outran c++ and turned out to be more than twice as fast. Python took 53 seconds, c++ took 1 minute and 54 seconds.

Is it because python has some special optimization done to the interpreter or is it because C++ has to refer to and std which slows it down and makes it take up ram?

Or is it some other reason?

Edit: I tried again, with instead of std::endl, and compiling with the -O3 flag, this time it took 1 min to reach 500,000.

解决方案

There isn't anything obvious here. Since Python's written in C, it must use something like printf to implement print. C++ I/O Streams, like cout, are usually implemented in a way that's much slower than printf. If you want to put C++ on a better footing, you can try changing to:

#include

int main()

{

int x=0;

while(x!=1000000)

{

++x;

std::printf("%d ", x);

}

return 0;

}

I did change to using ++x instead of x++. Years ago people thought that this was a worthwhile "optimization." I will have a heart attack if that change makes any difference in your program's performance (OTOH, I am positive that using std::printf will make a huge difference in runtime performance). Instead, I made the change simply because you aren't paying attention to what the value of x was before you incremented it, so I think it's useful to say that in code.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值