Dear experienced friends, I have a question about the speed of calling a function when I use the Python class. Suppose we have two scenarios:
- We define the function inside the class, and run this function when we use the class.
class play_in():
def __init__(self, n):
super().__init__()
self.running_time = n
def __call__(self):
output = play_in.calculate_running_time_in(self.running_time)
return print(output)
@staticmethod
def calculate_running_time_in(n):
t1 = time.time()
for _ in range(n):
c = 9999*9999/32
return time.time()-t1
- We define the function outside the class, and call this function inside the class.
# define fun outside
def calculate_running_time_out(n):
t1 = time.time()
for _ in range(n):
c = 9999*9999/32
return time.time()-t1
class play_out():
def __init__(self, n):
super().__init__()
self.running_time = n
def __call__(self):
output = calculate_running_time_out(self.running_time)
return print(output)
Then I run these two function-calling methods several times. However, the difference between them is not stable. Sometimes the in-calling is faster, sometimes the out-calling is faster.
test_time = 10000000
test_model_in = play_in(test_time)
test_model_in()
test_model_out = play_out(test_time)
test_model_out()
So I am wondering: Is there a difference (or theoretical difference) between these two calling methods? If so, which one is better?
Thank you so much in advance!