开发者

What is -s flag in the timeit module in Python?

From Python Cookbook

python timeit.py -s"import random" -s"x=range(10开发者_如何学编程0000); random.shuffle(x)" "sorted(x)"
10 loops, best of 3: 152 msec per loop

What does the -s flag do? Searched online, python help and SO. But did not find a good explanation. Thanks.


From Python's built-in help()

>>>import timeit
>>>help(timeit)

....
Command line usage:
    python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [--] [statement]

Options:
  -n/--number N: how many times to execute 'statement' (default: see below)
  -r/--repeat N: how many times to repeat the timer (default 3)
  -s/--setup S: statement to be executed once initially (default 'pass')
....


Rereading the docs, it may be the "executed once initially" phrasing that isn't as clear as it could be (i.e. nowhere does the documentation say why being able to do that is a useful feature).

The benefit of the -s setup lines is that they are executed outside the timing loop, but the code inside the timing loop can see values that they define.

So in the quoted example, only the sorted(x) part is timed - the actual creation of x occurs in the setup code beforehand.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜