I have to make a class with a couple of methods in it but at the end I have to measure 5 times of duration.
I was thinking about this code but I don't know if it's possible to add class into a timeit.timeit
statement.
class MyExcercise(Thread):
def run():
i = 0
while i <= 10000000:
i =1
if __name__ == "__main__":
import timeit
for _ in range(5):
a = timeit.timeit(MyExcercise(??????), number=1)
print(f'Time a is to: {a: .3f} second(s)')
How can I make this code ready to use with class? (for now it's only error)
Later I have to multiply a thread and a number of processes but for now, how can I deal with it?
Edit:
Code works without class (but I have to do this with class).
def run():
i = 0
while i <= 10000000:
i =1
if __name__ == "__main__":
import timeit
for _ in range(5):
a = timeit.timeit(run, number=1)
print(f'Time a is to: {a: .3f} second(s)')
Time a is to: 0.238 second(s)
Time a is to: 0.247 second(s)
Time a is to: 0.260 second(s)
Time a is to: 0.248 second(s)
Time a is to: 0.250 second(s)
Edit 2:
Yes, my task is to measure my process with one thread, then with 4 threads, next in 4 processors in my computer.
CodePudding user response:
You can pass globals()
as global
parameter in the timeit
method.
import timeit
class MyExercise():
def run(__self__):
i = 0
while i <= 10000000:
i = 1
if __name__ == "__main__":
for _ in range(5):
a = timeit.timeit("MyExercise().run()", globals=globals(), number=1)
print(f'Time a is to: {a: .3f} second(s)')
Output:
Time a is to: 0.387 second(s)
Time a is to: 0.383 second(s)
Time a is to: 0.382 second(s)
Time a is to: 0.381 second(s)
Time a is to: 0.382 second(s)
References: