简体   繁体   English

乘0比Python中的任何其他乘法快吗?

[英]Is multiplying by 0 faster than any other multiplication in Python?

I want to optimize matrix multiplications (weighs regression) in Python by masking some values I know I don't need in computations as zeros. 我想通过屏蔽一些我知道在计算中不需要为零的值来优化Python中的矩阵乘法(权衡回归)。 They will still be there as I don't want to change size of the matrices. 它们仍然会存在,因为我不想更改矩阵的大小。 Matrices are floats. 矩阵是浮点数。

Will Python (keras/tensorflow?) treat these multiplications in different way and significantly speed up the process, or it will take similar amount of time, making such masking pointless? Python(keras / tensorflow?)是否会以不同的方式处理这些乘法并显着加快处理速度,或者将花费相似的时间,从而使这种掩盖变得毫无意义?

No, the multiplying by zero is the same as multiplying by any other number 不,乘以零等于乘以任何其他数字

>>> def times_zero(x):
...     return x * 0
... 
>>> import dis
>>> dis.dis(times_zero)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (0)
              6 BINARY_MULTIPLY     
              7 RETURN_VALUE        
>>> def times_four(x):
...     return x * 4
... 
>>> dis.dis(times_four)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (4)
              6 BINARY_MULTIPLY     
              7 RETURN_VALUE   

I timed them: 我给他们计时:

from timeit import default_timer as timer
import itertools

my_toggle = itertools.cycle(range(2))

for x in range(20):
    current_number = my_toggle.__next__()
    start = timer()
    y = 1 * current_number
    end = timer()
    print(f"{end - start:.10f} seconds for {current_number}")

But I'm not sure what to make of the results: 但是我不确定结果如何:

0.0000002555 seconds for 0
0.0000002555 seconds for 1
0.0000002555 seconds for 0
0.0000002555 seconds for 1
0.0000002555 seconds for 0
0.0000000000 seconds for 1
0.0000000000 seconds for 0
0.0000002555 seconds for 1
0.0000000000 seconds for 0
0.0000000000 seconds for 1
0.0000000000 seconds for 0
0.0000002555 seconds for 1
0.0000002555 seconds for 0
0.0000000000 seconds for 1
0.0000002555 seconds for 0
0.0000000000 seconds for 1
0.0000000000 seconds for 0
0.0000002555 seconds for 1
0.0000000000 seconds for 0
0.0000000000 seconds for 1

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

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