测量小代码片段的执行时间时出现错误

I got an error when measuring execution time of small code snippets

这是doc
当我在 Windows cmd 上使用命令行界面时,出现此错误:

C:\Windows\system32>
C:\Windows\system32>python3 -m timeit '"-".join(str(n) for n in range(100))'
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Program Files\Python36\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Program Files\Python36\lib\timeit.py", line 362, in <module>
    sys.exit(main())
  File "C:\Program Files\Python36\lib\timeit.py", line 315, in main
    t = Timer(stmt, setup, timer)
  File "C:\Program Files\Python36\lib\timeit.py", line 123, in __init__
    compile(stmtprefix + stmt, dummy_src_name, "exec")
  File "<timeit-src>", line 2
    '-.join(str(n)
                 ^
SyntaxError: EOL while scanning string literal

C:\Windows\system32>

有人能帮帮我吗?

您可能需要转义 python 代码行。在提供的堆栈跟踪的最后一行,您可以看到 cmd 已经去掉了双引号。

在表达式的外部使用双引号,在表达式内部使用单引号。

python -m timeit "'-'.join(str(n) for n in range(100))"