timeit 模块因 pow() 值较大而挂起
我正在尝试计算 pow 函数计算指数模所需的时间。当 g、x、p 的值被硬编码时,代码会给出错误,而当这些值放置在 pow 函数中时,代码会挂起。当我使用 time() 和 Clock() 来计算这段代码所花费的时间时,同一段代码可以有效地工作。 我想要准确性,为此,在使用 Clock() 和 time() 函数进行测试后,我现在已转移到 timeit 模块。
该代码适用于较小的值,例如 pow(2, 3, 5),这是有意义的。如何提高使用 timeit 模块计算时间的效率。
另外,我是Python的初学者,如果代码中有任何愚蠢的错误,请原谅我。
import math
import random
import hashlib
import time
from timeit import Timer
g = 141802876407053547664378835005750805370737584038368838959151050908654130616798415530564917923311706921535439557793280725844349256960807398107370211978304
x = 1207729835787890214
p = 4870352607375058055471602136317178172283784073796673298937466544646468718314482464390112574915498953621226853454222898392076852427324057496200810018794472
t = Timer('pow(g,x,p)', 'import math')
z = t.timeit()
print ('the value of z is: '), z
谢谢
I am trying to calculate the time taken by pow function to calculate exponential modulo. With the values of g,x,p hardcoded the code gives error and with the values placed in the pow function, the code hangs. The same piece of code is working efficiently when i am using time() and clock() to calculate the time taken by this piece of code.
i wanted accuracy and for that now i have moved to timeit module after testing with clock() and time() functions.
The code works fine with small values such as pow(2, 3, 5) which makes sense. how can i improve the efficency to calculate time using timeit module.
Also i am a beginner to python, forgive me if there is any stupid mistake in the code.
import math
import random
import hashlib
import time
from timeit import Timer
g = 141802876407053547664378835005750805370737584038368838959151050908654130616798415530564917923311706921535439557793280725844349256960807398107370211978304
x = 1207729835787890214
p = 4870352607375058055471602136317178172283784073796673298937466544646468718314482464390112574915498953621226853454222898392076852427324057496200810018794472
t = Timer('pow(g,x,p)', 'import math')
z = t.timeit()
print ('the value of z is: '), z
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有两个问题:
您无法直接从
timeit
访问全局变量:请参阅这个问题。您可以使用它来修复错误:或者只是将数值直接放入字符串中。
默认情况下,timeit 模块运行 1000000 次迭代,这在这里会花费太长时间。您可以更改迭代次数,例如:
这将防止看起来像是挂起的情况(但实际上只是一个非常长的计算)。
There are two issues here:
You can't directly access globals from
timeit
: See this question. You can use this to fix the error:Or just put the numerical values directly in the string.
By default, the timeit module runs 1000000 iterations, which will take much too long here. You can change the number of iterations, for example:
This will prevent what seems like a hang (but is actually just a very long calculation).