簡體   English   中英

為什么我的 C++ 程序比 Python 版本慢 100 倍?

[英]Why my C++ program is 100x slower than a Python Version?

我想對一些編程語言進行比較,我拿了 C、C++ 和 Python。

這是我的測試循環的 C++ 代碼:

#include <iostream>


int main(){

for(int i=0;i<10000;i++){
std::cout<<i;
}

}

用 Code::blocks 的 GCC 編譯后(我認為它不會有很大的不同,而且這不僅僅是一個沒有優化的編譯問題,否則它只需要少 1000* 的時間),大約需要 3 ( 2 對於 C 版本)秒顯示全部(沒有換行符,給出文本湯)。

我做了一個簡單的 Python 版本:

for i in range(10000):
  print(i,end="")

它在 0.12 秒內運行。(使用 sys.write 0.05)

我的問題很簡單:為什么我的 C++ 程序這么慢? (相對於這個簡單的Python版本)

在 Windows 上,如果 output 是交互式控制台,則默認行為是不緩沖標准輸出。 當其他平台做類似的事情時,再加上默認的 Windows 控制台速度非常慢,這意味着如果你 output 給它很多文本,你的程序會很慢。

另一方面,Python 默認采用基於行的緩沖方法。 這樣它只會在運行時嘗試繪制到標准輸出一次。

對於 Python 端,如果您使用如下命令運行腳本:

python -u script_name.py

就控制台而言,它應該花費與 C/C++ 版本一樣長的時間,大致是因為它正在做相同數量的工作。

另一方面,如果您像這樣運行 C++ 程序:

    auto t1 = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < 10000; i++) {
        std::cout << i;
    }
    std::cout << std::endl;

    auto t2 = std::chrono::high_resolution_clock::now();
    setvbuf(stdout, NULL, _IOLBF, 8192);
    for (int i = 0; i < 10000; i++) {
        std::cout << i;
    }
    std::cout << std::endl;

    auto t3 = std::chrono::high_resolution_clock::now();

    std::cout << "Default behavior: " << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << std::endl;
    std::cout << "Buffered behavior: " << std::chrono::duration_cast<std::chrono::milliseconds>(t3 - t2).count() << std::endl;

這將顯示使用默認緩沖模式與更類似於 Python 緩沖技術的緩沖模式對性能的影響。

在我的機器上,它最后輸出這個,顯示緩沖速度超過 20 倍:

Default behavior: 751
Buffered behavior: 34

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM