0

I want to compare the processing speed of instance variables and function arguments.

I wrote the following code, but most of it took time to print.

How can I do a pure speed comparison?

import time class checkTime(): def __init__(self): self.a = 0 self.b = 0 self.c = 0 def printWithArgument(self,a,b,c): print(a+b+c) def printWithSelf(self): print(self.a+self.b+self.c) def getTime(self): printWithSelf_start = time.time() for i in range(0,100000): self.a = 1 self.b = 2 self.c = 3 self.printWithSelf() printWithSelf_elapsed_time = time.time() - printWithSelf_start printWithArgument_start = time.time() for i in range(0,100000): self.printWithArgument(1,2,3) printWithArgument_elapsed_time = time.time() - printWithArgument_start print ("printWithArgument_time:{0}".format(printWithArgument_elapsed_time) + "[sec]") print ("printWithSelf_time:{0}".format(printWithSelf_elapsed_time) + "[sec]") checkTime = checkTime() checkTime.getTime() 

1 Answer 1

2

I would recommend using timeit and not time for this:

import timeit class checkTime(): def __init__(self): self.a = 0 self.b = 0 self.c = 0 def printWithArgument(self,a,b,c): a+b+c def printWithSelf(self): self.a+self.b+self.c def getTime(self): def test1(): self.a = 1 self.b = 2 self.c = 3 self.printWithSelf() printWithSelf_elapsed_time = timeit.Timer(stmt=test1).repeat(number=100000) def test2(): self.printWithArgument(1,2,3) printWithArgument_elapsed_time = timeit.Timer(stmt=test2).repeat(number=100000) print ("printWithArgument_time:{0}".format(printWithArgument_elapsed_time) + "[sec]") print ("printWithSelf_time:{0}".format(printWithSelf_elapsed_time) + "[sec]") checkTime = checkTime() checkTime.getTime() 

Gives:

printWithArgument_time:[0.033693790435791016, 0.03463387489318848, 0.03436899185180664][sec] printWithSelf_time:[0.055680036544799805, 0.054234981536865234, 0.05341005325317383][sec] 

Arguments are about 40% faster than passing via instance variables. This is because that positional arguments can be passed and accessed without a dictionary lookup. Instance variables require a dictionary lookup on both assignment and access. This is also the reason why locals are faster than globals. Locals are stored in an array and accessed by index rather than in a dictionary indexed by name.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.