0

I was trying to benchmark code so I was trying this:

from timeit import *
from random import randint as ri
def linsearch(s,x):
   for i in range(len(s)):
       if s[i]==x:
          return

# Set up code
S = """     
    s = []
    for i in range(10):
       s.append(random.ri(0,10))
    x=s[5]
 """
# benchmark code
B="""    
  linsearch(s,x)
   """
p=10
m=100
t=min(Timer(B,S).repeat(10,100))
print("t:",t)

But this is not working. It is not recognizing random. I am using python 3.6. How should I correct my code?

Neil
  • 13,713
  • 3
  • 27
  • 50
A Q
  • 168
  • 2
  • 12

1 Answers1

2

timeit seems to run the code snippet in a separate interpreter environment, so you will have to import the things in the setup code.

from timeit import *
def linsearch(s,x):
   for i in range(len(s)):
       if s[i]==x:
          return

# Set up code
S = """
from __main__ import linsearch
from random import randint as ri
s = []
for i in range(10):
    s.append(ri(0,10))
x=s[5]
 """
# benchmark code
B="""
linsearch(s,x)
"""
p=10
m=100
t=min(Timer(B,S).repeat(10,100))
print("t:",t)