Professional Documents
Culture Documents
09 Costs
09 Costs
COMP 103 #9
Menu
• Assignment 3
• Undo: Rect/Oval -> Photo/Border
COMP103 2006/T3 2
Analysing Algorithms
COMP103 2006/T3 3
Analysing Costs
The costs of a program:
• Time:
• Run the program and count the milliseconds/minutes/days.
• Count number of steps/operations the algorithm will take.
• Space:
• Measure the amount of memory the program occupies
• Count the number of elementary data items the algorithm
stores.
• Question:
• Programs or Algorithms?
• Answer:
• Both are valuable:
• programs: benchmarking
• algorithms: analysis
COMP103 2006/T3 4
Benchmarking: program cost
• Measure: (Assignment 4 !!!)
• actual programs
• on real machines
• on specific input
• measure elapsed time
• measure real memory use
• Problems:
• what input ⇒ choose test sets carefully
use large data sets
don’t include user input
• other users/processes ⇒ minimise
average over many runs
• which computer? ⇒ specify details
COMP103 2006/T3 5
Benchmarking: program cost
COMP103 2006/T3 8
Pragmatics
• Count the most expensive actions:
• Adding 2 numbers is cheap
• Raising to a power is not so cheap
• Comparing 2 strings may be expensive
• Reading a line from a file may be very expensive
• Waiting for input from a user or another program may take
forever…
COMP103 2006/T3 9
Asymptotic Notation
• Big ‘O’
• We don’t care about small contributors.
• Focus on large contributors
• This is the dominant cost as n -> inf.
• So don’t need to care about any constants.
COMP103 2006/T3 10
ArrayList: get, set, remove
• Assume List contains n items.
• Cost of get and set:
• best, worst, average: O(1)
• ⇒ constant number of steps, regardless of n
• Cost of Remove:
n
• worst case:
• what is the worst case? from the front
• how many steps? n-1
• average case:
from the middle
• what is the average case?
• how many steps? n/2
COMP103 2006/T3 11
ArrayList: add
• Cost of add(index, value):
• what’s the key step? n
• worst case:
• average case:
• average case:
COMP103 2006/T3 14
ArrayList costs: Summary
• get O(1)
• set O(1)
• remove O(n)
• add (at i) O(n) (worst and average)
• add (at end) O(1) (average)
O(n) (worst)
O((2n-10)/n)
= O(1) (amortised average)
• Question:
• what would the cost be if the array size
is increased by 10 each time?
COMP103 2006/T3 15
Typical Costs in Big ‘O’
If data/input is size n
COMP103 2006/T3 16
Typical Costs
COMP103 2006/T3 17