Reputation: 284
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?
Upvotes: 2
Views: 95
Reputation: 1378
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).
def timeandsave(n, function, some_list, index=0):
start=0
my_list = copy.deepcopy(some_list)
gen(n, my_list)
#etc logic
return end
def timeandsave(n, function, some_tuple, index=0):
start=0
#etc logic
Upvotes: 1
Reputation: 182
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.
Upvotes: 0