Why is reading lines from stdin much slower in C++ than Python?

前端 未结 10 2006
野趣味
野趣味 2020-11-22 03:06

I wanted to compare reading lines of string input from stdin using Python and C++ and was shocked to see my C++ code run an order of magnitude slower than the equivalent Pyt

10条回答
  •  日久生厌
    2020-11-22 04:03

    Just out of curiosity I've taken a look at what happens under the hood, and I've used dtruss/strace on each test.

    C++

    ./a.out < in
    Saw 6512403 lines in 8 seconds.  Crunch speed: 814050
    

    syscalls sudo dtruss -c ./a.out < in

    CALL                                        COUNT
    __mac_syscall                                   1
    
    open                                            6
    pread                                           8
    mprotect                                       17
    mmap                                           22
    stat64                                         30
    read_nocancel                               25958
    

    Python

    ./a.py < in
    Read 6512402 lines in 1 seconds. LPS: 6512402
    

    syscalls sudo dtruss -c ./a.py < in

    CALL                                        COUNT
    __mac_syscall                                   1
    
    open                                            5
    pread                                           8
    mprotect                                       17
    mmap                                           21
    stat64                                         29
    

提交回复
热议问题