我想计算一段代码而不将它放在一个单独的函数中.例如:
def myfunc:
# some code here
t1 = time.time()
# block of code to time here
t2 = time.time()
print "Code took %s seconds." %(str(t2-t1))
Run Code Online (Sandbox Code Playgroud)
但是,我想以更干净的方式使用timeit模块执行此操作,但我不想为代码块创建单独的函数.
谢谢.
在我读到的关于timeit的所有地方,我发现只能以这种方式使用变量:
s1 = 'abc'
s2 = 'abc'
timeit.timeit('s1==s2', 'from __main__ import s1, s2', number=10**4)
Run Code Online (Sandbox Code Playgroud)
要么
s1 = 'abc'
s2 = 'abc'
def func():
timeit.time('s1==s2', 'from __main__ import s1,s2', number=10**4)
Run Code Online (Sandbox Code Playgroud)
which means that you can also use timeit.timeit in a function as long as the variables are in the main program. I would like to use timeit.timeit with variables that are within the scope it is in, for example:
def func():
s1 = 'abc'
s2 = 'abc'
timeit.timeit(...)
Run Code Online (Sandbox Code Playgroud)
As you …