哪种方法更快?

时间:2019-06-19 17:04:51

标签: python python-3.x performance

请考虑以下课程:

class SpeedAPI:

    def __init__(self):
        self.data = 1

    def execute_method(self):
        return True

from speed_api import SpeedAPI

class MyAPI:

    def __init__(self):
        self.data = 1

    def my_execute_method(self):
        SpeedAPI().execute_method()

我想测试每个类中每个方法的执行速度。我设计了以下测试来做到这一点:

from speed_api import SpeedAPI
from myapi import MyAPI
import time
import threading

def test_speed_for_SpeedAPI():
    time_trials_SpeedAPI = 0
    for i in range(10000):
        start_time = time.time()
        SpeedAPI().execute_method()
        end_time = time.time()
        calculated_time = (end_time - start_time)
        time_trials_SpeedAPI += calculated_time
    averaged_time = (time_trials_SpeedAPI / 10000)
    print(averaged_time)

def test_speed_for_MyAPI():
    time_trials_MyAPI = 0
    for i in range(10000):
        start_time = time.time()
        MyAPI().my_execute_method()
        end_time = time.time()
        calculated_time = (end_time - start_time)
        time_trials_MyAPI += calculated_time
    averaged_time = (time_trials_MyAPI / 10000)
    print(averaged_time)

threads = [threading.Thread(target=test_speed_for_SpeedAPI), threading.Thread(target=test_speed_for_MyAPI)]

print('Testing speed for SpeedAPI')
threads[0].start()
threads[0].join()
print('Testing speed for MyAPI')
threads[1].start()
threads[1].join()

但是,在运行了几次测试之后,我发现存在不一致之处。有时MyAPISpeedAPI快。最终,我期望SpeedAPI变得更快。我期望这个错误吗?我确实意识到两者之间执行时间的差异很小。但是,我仍然对知道哪种更快以及为什么更快感兴趣。

以下是一些示例测试结果:

Testing speed for SpeedAPI
5.976438522338867e-07
Testing speed for MyAPI
8.997201919555664e-07

Testing speed for SpeedAPI
4.0011405944824217e-07
Testing speed for MyAPI
8.000850677490234e-07

Testing speed for SpeedAPI
4.0068626403808596e-07
Testing speed for MyAPI
9.995698928833008e-07

Testing speed for SpeedAPI
5.038022994995118e-07
Testing speed for MyAPI
1.0046958923339845e-06

很明显,最后一次试验显示出不一致之处。这可能是什么原因?可能与我运行每个测试的速度有多快吗?我正在手动运行它,并一遍又一遍地通过执行脚本向终端发送垃圾邮件。感谢所有提前答复的人。

0 个答案:

没有答案