-2

I have a problem with doing timeit for python. Here is codes

 import timeit
>>> iteration_test = """
     for i in itr :
         pass
         """
>>> 
>>> timeit.timeit(iteration_test, setup='itr = list(range(10000))', number=1000)

I tried tab solution but it didn't work. What is the problem?

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • 2
    If your code really looks exactly like that, the problem is that your `for` loop is indented. It should not be indented. – Tim Roberts Jul 19 '21 at 06:58
  • """ is opened and closed for text records but you are using it in for loop that was the issue – arun n a Jul 19 '21 at 08:36
  • There is a duplicate with a good explanation: https://stackoverflow.com/questions/23666307/timeit-module-in-python-does-not-run-correctly – Thierry Lathuille Jul 19 '21 at 08:37

3 Answers3

1

write your code like this -

iteration_test = """ 
for i in itr : 
    pass 
"""

timeit.timeit(iteration_test, setup='itr = list(range(10000))', number=1000)
PCM
  • 2,881
  • 2
  • 8
  • 30
  • It matters because now no error. Python's triple quote strings starts from global scope even though it is written under a function – PCM Jul 19 '21 at 06:59
  • @Sujay, have you tried the code. It works fine. 3 quoted strings also takes in indentation. Unlike single quotes or double which ignores initial indentation – PCM Jul 19 '21 at 07:01
  • @Sujay Indentations do matter in strings, when the string contains Python code that is supposed to be correct. As PCM says, try it. – BoarGules Jul 19 '21 at 08:04
1

You entered a tab at the begining of your for statement. Try this:

    import timeit
    
    iteration_test = """for i in itr : pass """
    
    timeit.timeit(iteration_test, setup='itr = list(range(10000))', number=1000)
Agent Biscutt
  • 712
  • 4
  • 17
0

space in the three quotes(multiline string) are considered part of the string. python multi line strings even if the variable name has space before it the string should not have spaces in it. it may not look correct in first view but logically it makes sense

for example...

  iteration_test = """
for i in itr:
  pass
"""
ManishSingh
  • 1,016
  • 11
  • 9