繁体   English   中英

为什么python在for循环中击败c ++?

[英]Why does python beat c++ in for loops?

这是我的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;
    }
    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代码:

import time

def foo():
    start = time.time()
    for i in range(1000):
        print('Test')
    print('Duration: {}'.format(time.time()-start))

# This takes around ~ .08 secs on average

为什么在这种情况下PYTHON更快? 我不确定是否是因为我是否编写了额外的代码,但这似乎是一个非常基本的for循环。

不是for循环慢,而是C ++ iostreams 甚至不是iostreams太慢了, 1而是您为每一行都做了一个endl

C ++ endl不仅是'\\n'的同义词,它还是一个io操作器对象,当插入到流中时,它会插入'\\n' 然后要求将流刷新。 冲洗标准输出可能非常慢。

另一方面,除非您明确要求,Python print不会刷新。 否则,它只会写入sys.stdout ,这是一个TextIOWrapper ,它将内容存储在缓冲区中,并在认为合适时刷新该值,这与C ++ iostreams几乎相同。 2

为了进行公平的测试,请对此进行比较:

    cout << "Test\n";

    print("Test")

… 或这个:

    cout << "Test" << endl;

    print("Test", flush=True)

1.某些平台/编译器/优化的标志,它相当缓慢的。 机械手的速度可能特别慢。 因此,在解决此问题后,Python可能仍会击败C ++。 但不是以11:1的比例。

2. Python还必须将字符串从Unicode转换为sys.stdout.encoding 但是,如果您使用的是3.4或更高版本,则将像'test''test'全都是ASCII的Unicode字符串存储为ASCII字节,并且对其进行编码是无操作的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM