Performance effect of using print statements in Python script

后端 未结 2 765
醉话见心
醉话见心 2020-12-15 03:43

I have a Python script that process a huge text file (with around 4 millon lines) and writes the data into two separate files.

I have added a print statement, which

2条回答
  •  Happy的楠姐
    2020-12-15 04:18

    Tried doing it in a very simple script just for fun, the difference is quite staggering:

    In large.py:

    target =  open('target.txt', 'w')
    
    for item in xrange(4000000):
        target.write(str(item)+'\n')
        print item
    

    Timing it:

    [gp@imdev1 /tmp]$ time python large.py
    real    1m51.690s
    user    0m10.531s
    sys     0m6.129s
    
    gp@imdev1 /tmp]$ ls -lah target.txt 
    -rw-rw-r--. 1 gp gp 30M Nov  8 16:06 target.txt
    

    Now running the same with "print" commented out:

    gp@imdev1 /tmp]$ time python large.py 
    real    0m2.584s
    user    0m2.536s
    sys     0m0.040s
    

提交回复
热议问题