views:

31

answers:

2

Dear All,

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

+3  A: 

There are two issues here:

  1. You can't directly access globals from timeit: See this question. You can use this to fix the error:

    t = Timer('pow(g,x,p)', 'from __main__ import g,x,p')
    

    Or just put the numerical values directly in the string.

  2. By default, the timeit module runs 1000000 iterations, which will take much too long here. You can change the number of iterations, for example:

    z = t.timeit(1000)
    

    This will prevent what seems like a hang (but is actually just a very long calculation).

interjay
+1 - faster than me and better worded. Bowing out gracefully now :)
Tim Pietzcker
A: 

so large number, cannot work.

chenge