Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save johndpope/d22970b54f6c6cde4d37cc3376f61a18 to your computer and use it in GitHub Desktop.
Save johndpope/d22970b54f6c6cde4d37cc3376f61a18 to your computer and use it in GitHub Desktop.
Calculate execution time for a block of Swift code
import QuartzCore
func executionTimeInterval(block: () -> ()) -> CFTimeInterval {
let start = CACurrentMediaTime()
block();
let end = CACurrentMediaTime()
return end - start
}
// DEMO (paste all this into a playground)
// Non-memoized Fibonacci generator
func fib(n: Int) -> Int {
assert(n >= 0)
switch n {
case 0, 1: return 1
default: return fib(n-1) + fib(n-2)
}
}
let fib8 = executionTimeInterval {
let x = fib(8)
print("fib(8) = \(x)")
}
let fib10 = executionTimeInterval {
let x = fib(10)
print("fib(10) = \(x)")
}
let fib12 = executionTimeInterval {
let x = fib(12)
print("fib(12) = \(x)")
}
@johndpope
Copy link
Author

launch

@johndpope
Copy link
Author

screen shot 2018-09-07 at 17 42 19

screen shot 2018-09-07 at 17 42 10

@johndpope
Copy link
Author

screen shot 2018-09-07 at 19 48 12

@johndpope
Copy link
Author

screen shot 2018-09-09 at 11 28 23

@johndpope
Copy link
Author

gymai

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment