Timeit 模块拒绝 print("\n") 语句
Timeit module is rejecting print("\n") statements
我正在尝试运行下面的代码示例
from timeit import timeit as t
setup = '''
import time
from multiprocessing import Pool
def square(x):
square = x * x
time.sleep(1)
return square
'''
case01 = '''
def caso01():
print("\nPART 1")
starttime = time.time()
pool = Pool(4)
pool.map(square, range(0, 5))
pool.close()
endtime1 = time.time()
print(f"Time taken {endtime1-starttime} seconds")
return None
'''
def main():
print( t(setup=setup,stmt=case01,number=100) )
return None
main()
我总是得到同样的错误:
File "/usr/lib/python3.8/timeit.py", line 233, in timeit
return Timer(stmt, setup, timer, globals).timeit(number)
File "/usr/lib/python3.8/timeit.py", line 122, in __init__
compile(stmtprefix + stmt, dummy_src_name, "exec")
File "<timeit-src>", line 16
print("
我发现从打印语句中删除“\n”问题就消失了。 Timeit 模块根本不能使用“\n”吗?我错过了什么?
谢谢
PS:在 linux 机器上使用 Python 3
您需要添加前导反斜杠 (\
) 来转义 \n
,因为它在运行时被解码。
case01 = '''
def caso01():
print("\nPART 1")
starttime = time.time()
pool = Pool(4)
pool.map(square, range(0, 5))
pool.close()
endtime1 = time.time()
print(f"Time taken {endtime1-starttime} seconds")
return None
'''
我正在尝试运行下面的代码示例
from timeit import timeit as t
setup = '''
import time
from multiprocessing import Pool
def square(x):
square = x * x
time.sleep(1)
return square
'''
case01 = '''
def caso01():
print("\nPART 1")
starttime = time.time()
pool = Pool(4)
pool.map(square, range(0, 5))
pool.close()
endtime1 = time.time()
print(f"Time taken {endtime1-starttime} seconds")
return None
'''
def main():
print( t(setup=setup,stmt=case01,number=100) )
return None
main()
我总是得到同样的错误:
File "/usr/lib/python3.8/timeit.py", line 233, in timeit
return Timer(stmt, setup, timer, globals).timeit(number)
File "/usr/lib/python3.8/timeit.py", line 122, in __init__
compile(stmtprefix + stmt, dummy_src_name, "exec")
File "<timeit-src>", line 16
print("
我发现从打印语句中删除“\n”问题就消失了。 Timeit 模块根本不能使用“\n”吗?我错过了什么?
谢谢
PS:在 linux 机器上使用 Python 3
您需要添加前导反斜杠 (\
) 来转义 \n
,因为它在运行时被解码。
case01 = '''
def caso01():
print("\nPART 1")
starttime = time.time()
pool = Pool(4)
pool.map(square, range(0, 5))
pool.close()
endtime1 = time.time()
print(f"Time taken {endtime1-starttime} seconds")
return None
'''