Time measurement - many measurements and variable in an iterval

96 views Asked by At

I am to measure how long does it take for my function to represent C:

C in range (0, 100, 1)

with integers from a list which is given. There is my code:

import itertools
import time    
def amount(c):
    a = [1, 2, 5, 10, 20, 50]

    dp = [[0 for _ in range(len(a))] for __ in range(c + 1)]
    dp[0][0] = 1

    for i in range(c):
        for j in range(len(a)):
            for k in range(j, len(a)):
                if i + a[k] <= c:
                     dp[i + a[k]][k] += dp[i][j]

    return sum(dp[c])

I decided to create a function which measures how long does one call of my function last:

def count_once(c):
    start = time.perf_counter()
    amount(c)
    return time.perf_counter() - start

It's pretty easy. Now I would like to make 10 measurements for each C from 0 to 100 and then to count the average from those measurements for each C.
So the output should contain 100 numbers (each number would be the average).
I started with this:

for i in range(0, 101, 1):
    count_once(i)
    print(count_once(i))

But I have no idea how can I use that formula to calculate an average of 10 measurements for each C.

1

There are 1 answers

4
kabanus On BEST ANSWER

Why not:

for C in range(100):
     print "C=",C,"averages",sum([count_once(C) for_ in range(10)])/10.0

You can easily change the first range(100) with any list/iterable of C values you want to test, and the 10s on the second line with the amount you want to average over.

By the way to eliminate the timing overhead I would go about this a bit differently:

def count(c,times):
    start = time.perf_counter()
    for _ in range(times): amount(c)
    return (time.perf_counter() - start)/float(times)

Then your outer loop becomes:

for C in range(100): print "C=",C,"averages",count(C,10)

I would probably use more times than 10 (say 100 or 1000 at least).