English 中文(简体)
复制品a
原标题:Multiplications a*b vs a*0: execution time

Action 1: Multiplication of a random number a with another random number b Action 2: Multiplication of the same number a with 0

我进行了小规模试验,看看其中哪些行动的执行时间最小。 因此,我写了下文的小方案,即行动1,大量时间衡量其全部执行时间,并重复行动2,看看两者间执行时间最小的情况。 我重复了上述100次,以产生更可靠的结果。

执行该方案,以发现出于某种原因,行动1在大部分时间(约75%)中加快行动2。 对类似情况的解释是什么?

import time
import numpy as np

def compare_execution_times(a, b):
    # Measure the execution time of multiplication with non-zero b
    start_time = time.time()
    for _ in range(1000000):  # Perform multiplication a large number of times
        result = a * b
    end_time = time.time()
    first_execution_time = end_time - start_time
    
    # Measure the execution time of multiplication with zero b
    start_time = time.time()
    for _ in range(1000000):  # Perform multiplication a large number of times
        result = a * 0
    end_time = time.time()
    second_execution_time = end_time - start_time
    
    return first_execution_time < second_execution_time

count_true = 0
count_false = 0
for _ in range(100):
    a = np.random.rand()  # Generate random a
    b = np.random.rand()  # Generate random b
    if compare_execution_times(a, b):
        count_true += 1
    else:
        count_false += 1

print("
Number of times first execution was smaller:", count_true)
print("Number of times second execution was smaller:", count_false)
问题回答
  1. <代码>时间:对于衡量优秀业绩来说是可怕的。timeit 模块,或%timeitmagic in IPython,处理一个lot小差错,可随时间推移产生。

  2. 您与浮动点值,而不是ints,就您的<代码>a和b进行比较,因此,只有在以<代码>0而不是以<代码>b乘数时,才会涉及这类转换。 令我感到惊讶的是,不匹配的类型比相应的类型更加昂贵。 将字面改为0.0.0 可能减少零的操作时间。

如果你想要进行合法比较,这里就是一个使用纯粹的<条码>float的例子:

In [1]: %%timeit import random; a, b = random.random(), random.random()
   ...: a*b
   ...:
   ...:
13.6 ns ± 0.13 ns per loop (mean ± std. dev. of 7 runs, 100,000,000 loops each)

In [2]: %%timeit import random; a, b = random.random(), random.random()
   ...: a*0.0
   ...:
   ...:
13.2 ns ± 0.105 ns per loop (mean ± std. dev. of 7 runs, 100,000,000 loops each)

(脚注一使用的0.0,其字面为,而不是int)和纯< <>t。

In [3]: %%timeit import random; a, b = random.randrange(16), random.randrange(16)
    ...: a*b
    ...:
    ...:
11.4 ns ± 0.986 ns per loop (mean ± std. dev. of 7 runs, 100,000,000 loops each)

In [4]: %%timeit import random; a, b = random.randrange(16), random.randrange(16)
   ...: a*0
   ...:
   ...:
11.3 ns ± 0.33 ns per loop (mean ± std. dev. of 7 runs, 100,000,000 loops each)

在这两种情况下,乘数以零的速度略快,但还不够(在第二种情况下,时间如此接近,我怀疑时间在统计上是微不足道的;我只看到一个赢家,如果我允许<条码>>兰德兰高于16条,就会产生新的<条码><>int>/code>,而不是从小的<条码>(<>int cache)。

Fwiw, here s disassembly of You function:

  7           0 LOAD_GLOBAL              0 (time)
              2 LOAD_METHOD              0 (time)
              4 CALL_METHOD              0
              6 STORE_FAST               2 (start_time)

  8           8 LOAD_GLOBAL              1 (range)
             10 LOAD_CONST               1 (1000000)
             12 CALL_FUNCTION            1
             14 GET_ITER
        >>   16 FOR_ITER                 6 (to 30)
             18 STORE_FAST               3 (_)

  9          20 LOAD_FAST                0 (a)
             22 LOAD_FAST                1 (b)
             24 BINARY_MULTIPLY
             26 STORE_FAST               4 (result)
             28 JUMP_ABSOLUTE            8 (to 16)

 10     >>   30 LOAD_GLOBAL              0 (time)
             32 LOAD_METHOD              0 (time)
             34 CALL_METHOD              0
             36 STORE_FAST               5 (end_time)

 11          38 LOAD_FAST                5 (end_time)
             40 LOAD_FAST                2 (start_time)
             42 BINARY_SUBTRACT
             44 STORE_FAST               6 (first_execution_time)

 14          46 LOAD_GLOBAL              0 (time)
             48 LOAD_METHOD              0 (time)
             50 CALL_METHOD              0
             52 STORE_FAST               2 (start_time)

 15          54 LOAD_GLOBAL              1 (range)
             56 LOAD_CONST               1 (1000000)
             58 CALL_FUNCTION            1
             60 GET_ITER
        >>   62 FOR_ITER                 6 (to 76)
             64 STORE_FAST               3 (_)

 16          66 LOAD_FAST                0 (a)
             68 LOAD_CONST               2 (0)
             70 BINARY_MULTIPLY
             72 STORE_FAST               4 (result)
             74 JUMP_ABSOLUTE           31 (to 62)

 17     >>   76 LOAD_GLOBAL              0 (time)
             78 LOAD_METHOD              0 (time)
             80 CALL_METHOD              0
             82 STORE_FAST               5 (end_time)

 18          84 LOAD_FAST                5 (end_time)
             86 LOAD_FAST                2 (start_time)
             88 BINARY_SUBTRACT
             90 STORE_FAST               7 (second_execution_time)

 20          92 LOAD_FAST                6 (first_execution_time)
             94 LOAD_FAST                7 (second_execution_time)
             96 COMPARE_OP               0 (<)

I m 不能确定联络处如何 FAST and LOAD_ 比较业绩,但法典如何统一至少存在差别。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签