Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

Timing complexity for copy() in python. How do I add the elapsed time?

import timeit

def copytest():

lst = []
for i in range(1000000):
    lst.append(i)
starttime = timeit.default_timer()
copiedlst = lst.copy()
endtime = timeit.default_timer()
elapsedtime = endtime - starttime
elapsedtime += elapsedtime
return elapsedtime 

for j in range(1, 100):
    print(j, copytest())

I am trying to see how long it takes for copy() to copy a list. It should be O(n) because copy() is going through the list one item at a time. How do I get "elapsedtime" to keep track of the value it has had before? This code resets the elapsed time back to 0. I'd appreciate any help to fixing the code even more also!

question from:https://stackoverflow.com/questions/65941554/timing-complexity-for-copy-in-python-how-do-i-add-the-elapsed-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to have all the previous values for elapsedtime use the below code. elapsed_list holds these values for you.

import timeit

def copytest():
  lst = []
  for i in range(1000000):
      lst.append(i)
  starttime = timeit.default_timer()
  copiedlst = lst.copy()
  endtime = timeit.default_timer()
  elapsedtime = endtime - starttime
  elapsedtime += elapsedtime
  return elapsedtime 

elapsed_list = []
for j in range(1, 100):
  e = copytest()
  elapsed_list.append(e)
  print(j, copytest())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...