numpy float: 10x slower than builtin in arithmetic operations?

前端 未结 8 1042
别跟我提以往
别跟我提以往 2020-12-01 05:00

I am getting really weird timings for the following code:

import numpy as np
s = 0
for i in range(10000000):
    s += np.float64(1) # replace with np.float32         


        
相关标签:
8条回答
  • 2020-12-01 05:53

    Really strange...I confirm the results in Ubuntu 11.04 32bit, python 2.7.1, numpy 1.5.1 (official packages):

    import numpy as np
    def testfloat():
        s = 0
        for i in range(10000000):  
            s+= float(1)
    def testfloat32():
        s = 0
        for i in range(10000000):  
            s+= np.float32(1)
    def testfloat64():
        s = 0
        for i in range(10000000):  
            s+= np.float64(1)
    
    %time testfloat()
    CPU times: user 4.66 s, sys: 0.06 s, total: 4.73 s
    Wall time: 4.74 s
    
    %time testfloat64()
    CPU times: user 11.43 s, sys: 0.07 s, total: 11.50 s
    Wall time: 11.57 s
    
    
    %time testfloat32()
    CPU times: user 47.99 s, sys: 0.09 s, total: 48.08 s
    Wall time: 48.23 s
    

    I don't see why float32 should be 5 times slower that float64.

    0 讨论(0)
  • 2020-12-01 05:54

    Perhaps, that is why you should use Numpy directly instead of using loops.

    s1 = np.ones(10000000, dtype=np.float)
    s2 = np.ones(10000000, dtype=np.float32)
    s3 = np.ones(10000000, dtype=np.float64)
    
    np.sum(s1) <-- 17.3 ms
    np.sum(s2) <-- 15.8 ms
    np.sum(s3) <-- 17.3 ms
    
    0 讨论(0)
提交回复
热议问题