簡體   English   中英

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

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

我想通過屏蔽一些我知道在計算中不需要為零的值來優化Python中的矩陣乘法(權衡回歸)。 它們仍然會存在,因為我不想更改矩陣的大小。 矩陣是浮點數。

Python(keras / tensorflow?)是否會以不同的方式處理這些乘法並顯着加快處理速度,或者將花費相似的時間,從而使這種掩蓋變得毫無意義?

不,乘以零等於乘以任何其他數字

>>> 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   

我給他們計時:

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}")

但是我不確定結果如何:

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