-1

print function is called many times.I want to calculate function's time.I wrote codes,

import timeit

class UserClass:
    def callname(self):
        print("HiTom")

if __name__ == '__main__':
    def test():
        user = UserClass()
        user.callname()

    test()
    mtime = timeit.timeit(lambda: test())
    print(mtime)

When I run the codes,"Hi Tom" is called many times. I really cannot understand why such a thing happens.

I rewrote

mtime = timeit.timeit(test(), number=1)

but ValueError: stmt is neither a string nor callable error happens.How can I make my ideal system?What is wrong in my codes?

cs95
  • 379,657
  • 97
  • 704
  • 746
user9673470
  • 79
  • 1
  • 1
  • 6
  • 1
    Why wouldn't it be? That's what timeit *does*, calls what you provide it many times to get an average execution time. What were you *expecting* to happen? – jonrsharpe May 10 '18 at 07:31
  • Not too familiar with Python, but how about `mtime = timeit.timeit(lambda: test(), number=1)` – caylee May 10 '18 at 07:33
  • Thanks for accepting. You can also upvote answers if they were helpful (click the little triangle above the 0 to the left of my answer). Thanks again! – cs95 May 10 '18 at 09:12

1 Answers1

1

You'll have to

  1. pass a string to the stmt field, and
  2. pass a globals dict in order for timeit to figure out where the test function comes from

>>> timeit.timeit("test()", number=1, globals=globals())
HiTom
3.45029984600842e-05
cs95
  • 379,657
  • 97
  • 704
  • 746