Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Class into a timeit funkction

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading