简体   繁体   中英

Measuring time in Python

I have a function with measuring duration of other function and saving it in specific file:

def timeandsave(n, function, some_list, index=0):
    start=0
    gen(n, some_list)
    start = time.time()
    function(some_list)
    end = time.time() - start
    print 'Time: ' + str(end)
    plik = open('Sort' + str(n) + '_ind' + str(index) + '_result.txt', 'a')
    plik.write(str(end) + '\n')
    plik.close()
    return end

Now when I'm using for example:

timeandsave(10000, quick_sort_r, list, 1)

The answer is correct:

Time: 0.166000127792

But when I want to use it few times in a loop it's printing and saving a sum of results:

Input:
for i in range(0, 5):
    timeandsave(10000, quick_sort_r, list, 1)

Output:
Time: 0.173000097275
Time: 0.375999927521
Time: 0.577000141144
Time: 0.772000074387
Time: 0.962000131607

Any advice?

First of all have a look at this link : http://docs.python.org/2/library/timeit.html

Now for your code :
In your main program you are passing list as an argument, this is assigned to some_list which is part of the parameter. Now if you modify some_list; even list will get modified.
Most probably when you use gen() you are modifying the size of some_list, in turn modifying 'list' itself.
when you pass the list to some_copy, do a deep copy first or use a tuple instead of a list. (the latter is recommended).

option 1 :

def timeandsave(n, function, some_list, index=0):
  start=0
  my_list = copy.deepcopy(some_list)
  gen(n, my_list)
  #etc logic
  return end

option 2 :

def timeandsave(n, function, some_tuple, index=0):
  start=0
  #etc logic

timeandsave returns the time it took to perform the function, so you can use this to find an average:

def runTrials(trials, n, func, list):
    total= 0.0
    for _ in range(trials):
        total+= timeandsave(n, func, list, 1)
    average= total/ trials
    file= open('AVERAGES.txt', 'a')
    file.write('Trials: '+str(trials)+ ', average: '+ str(average))

if you are using python 2, replace range() with xrange() , it will reduce memory usage. Also take a look at python's timeit module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM