Advertisement
Guest User

Untitled

a guest
Oct 24th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. //: Playground - noun: a place where code can play
  2.  
  3. import UIKit
  4.  
  5. //Most precise time keeper
  6. // for more information on the benchmarks go to www.kandelvijaya.com
  7.  
  8. func timeBlockWithMach(_ block: () -> Void) -> TimeInterval {
  9. var info = mach_timebase_info()
  10. guard mach_timebase_info(&info) == KERN_SUCCESS else { return -1 }
  11.  
  12. let start = mach_absolute_time()
  13. block()
  14. let end = mach_absolute_time()
  15.  
  16. let elapsed = end - start
  17.  
  18. let nanos = elapsed * UInt64(info.numer) / UInt64(info.denom)
  19. return TimeInterval(nanos) / TimeInterval(NSEC_PER_SEC)
  20. }
  21.  
  22.  
  23. func test() {
  24. let rtDate = timeBlockWithMach{
  25. NSDate().timeIntervalSince1970
  26. }
  27.  
  28. let rtMedia = timeBlockWithMach {
  29. CACurrentMediaTime()
  30. }
  31.  
  32. let rtAbsolute = timeBlockWithMach {
  33. CFAbsoluteTimeGetCurrent()
  34. }
  35.  
  36. var time = timeval()
  37. let rtTimeOfDay = timeBlockWithMach {
  38. gettimeofday(&time, nil)
  39. }
  40.  
  41. let rtTimeWithMach = timeBlockWithMach {
  42. mach_absolute_time()
  43. }
  44.  
  45. let rtTimeWithProcessInfo = timeBlockWithMach {
  46. ProcessInfo.processInfo.systemUptime
  47. }
  48. }
  49.  
  50. test()
  51.  
  52.  
  53. // MARK: - Other timing functions
  54. func timeBlockWithDateTime(_ block: () -> Void) -> TimeInterval {
  55. let start = NSDate().timeIntervalSince1970
  56. block()
  57. let end = NSDate().timeIntervalSince1970
  58. return end - start
  59. }
  60.  
  61. func timeBlockWithCAMediaTiming(_ block: () -> Void) -> TimeInterval {
  62. let start = CACurrentMediaTime()
  63. block()
  64. let end = CACurrentMediaTime()
  65. return end - start
  66. }
  67.  
  68. func timeBlockWithCFTime(_ block: () -> Void) -> TimeInterval {
  69. let start = CFAbsoluteTimeGetCurrent()
  70. block()
  71. let end = CFAbsoluteTimeGetCurrent()
  72. return end - start
  73. }
  74.  
  75. func timeBlockWithGetTimeOfDay(_ block: () -> Void) -> TimeInterval {
  76. var start = timeval()
  77. gettimeofday(&start, nil)
  78. block()
  79. var end = timeval()
  80. gettimeofday(&end, nil)
  81.  
  82. return Double(start.tv_usec - end.tv_usec)
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement