TimeM: Time Complexity Monad #
TimeM T α represents a computation that produces a value of type α and tracks its time cost.
T is usually instantiated as ℕ to count operations, but can be instantiated as ℝ to count
actual wall time, or as more complex types in order to model more general costs.
Design Principles #
- Pure inputs, timed outputs: Functions take plain values and return
TimeMresults - Time annotations are trusted: The
timefield is NOT verified against actual cost. You must manually ensure annotations match the algorithm's complexity in your cost model. - Separation of concerns: Prove correctness properties on
.ret, prove complexity on.time
Cost Model #
Document your cost model explicitly Decide and be consistent about:
- What costs 1 unit? (comparison, arithmetic operation, etc.)
- What is free? (variable lookup, pattern matching, etc.)
- Recursive calls: Do you charge for the call itself?
Notation #
✓: A tick of time, seetick.⟪tm⟫: Extract the pure value from aTimeMcomputation (notation fortm.ret)
References #
See [Dan08] for the discussion.
A monad for tracking time complexity of computations.
TimeM T α represents a computation that returns a value of type α
and accumulates a time cost (represented as a type T, typically ℕ).
- ret : α
The return value of the computation
- time : T
The accumulated time cost of the computation
Instances For
Lifts a pure value into a TimeM computation with zero time cost.
Prefer to use pure instead of TimeM.pure.
Equations
- Cslib.Algorithms.Lean.TimeM.pure a = { ret := a, time := 0 }
Instances For
Equations
- Cslib.Algorithms.Lean.TimeM.instPureOfZero = { pure := fun {α : Type ?u.14} => Cslib.Algorithms.Lean.TimeM.pure }
Equations
- Cslib.Algorithms.Lean.TimeM.instBindOfAdd = { bind := fun {α β : Type ?u.15} => Cslib.Algorithms.Lean.TimeM.bind }
Equations
- Cslib.Algorithms.Lean.TimeM.instFunctor = { map := fun {α β : Type ?u.18} (f : α → β) (x : Cslib.Algorithms.Lean.TimeM T α) => { ret := f x.ret, time := x.time } }
TimeM is lawful so long as addition in the cost is associative and absorbs zero.
Creates a TimeM computation with a time cost.
Equations
- Cslib.Algorithms.Lean.TimeM.tick c = { ret := PUnit.unit, time := c }
Instances For
✓[c] x adds c ticks, then executes x.
Equations
- One or more equations did not get rendered due to their size.
Instances For
✓ x is a shorthand for ✓[1] x, which adds one tick and executes x.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Notation for extracting the return value from a TimeM computation: ⟪tm⟫
Equations
- One or more equations did not get rendered due to their size.