相关疑难解决方法(0)

Python中的代码时序块,无需将其放入函数中

我想计算一段代码而不将它放在一个单独的函数中.例如:

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模块执行此操作,但我不想为代码块创建单独的函数.

谢谢.

python benchmarking datetime

12
推荐指数
1
解决办法
3645
查看次数

Python 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 …

python string variables scope timeit

5
推荐指数
1
解决办法
5298
查看次数

标签 统计

python ×2

benchmarking ×1

datetime ×1

scope ×1

string ×1

timeit ×1

variables ×1