├── Tests ├── LinuxMain.swift └── DurationTests │ ├── XCTestManifests.swift │ └── DurationTests.swift ├── .travis.yml ├── Package.swift ├── README.md ├── .gitignore ├── Sources └── Duration │ └── Duration.swift └── LICENSE /Tests/LinuxMain.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | 3 | import DurationTests 4 | 5 | var tests = [XCTestCaseEntry]() 6 | tests += DurationTests.allTests() 7 | XCTMain(tests) 8 | -------------------------------------------------------------------------------- /Tests/DurationTests/XCTestManifests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | 3 | #if !canImport(ObjectiveC) 4 | public func allTests() -> [XCTestCaseEntry] { 5 | return [ 6 | testCase(DurationTests.allTests), 7 | ] 8 | } 9 | #endif 10 | -------------------------------------------------------------------------------- /Tests/DurationTests/DurationTests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | @testable import Duration 3 | 4 | final class DurationTests: XCTestCase { 5 | func testExample() { 6 | // This is an example of a functional test case. 7 | // Use XCTAssert and related functions to verify your tests produce the correct 8 | // results. 9 | XCTAssertEqual(Duration().text, "Hello, World!") 10 | } 11 | 12 | static var allTests = [ 13 | ("testExample", testExample), 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Travis CI build file for Swift Studies projects. 2 | # Tests with runs on OS X and Linux. 3 | # Uses IBM's PackageBuilder to complete builds on macOS and Linux 4 | # See the following URLs for further details on Travis CI with Swift 5 | # https://docs.travis-ci.com/user/languages/objective-c/ 6 | # https://docs.travis-ci.com/user/customizing-the-build/ 7 | # https://docs.travis-ci.com/user/docker/ 8 | # https://docs.travis-ci.com/user/multi-os/ 9 | 10 | # whitelist (branches that should be built) 11 | branches: 12 | only: 13 | - master 14 | - develop 15 | - /^issue.*$/ 16 | env: 17 | - SWIFT_VERSION=5.2.1 18 | 19 | os: 20 | - linux 21 | - osx 22 | language: generic 23 | sudo: required 24 | dist: bionic 25 | osx_image: xcode11.3 26 | install: 27 | - eval "$(curl -sL https://swiftenv.fuller.li/install.sh)" 28 | 29 | script: 30 | - swift build 31 | # - swift build -c release 32 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.1 2 | // Copyright 2016 Swift Studies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | import PackageDescription 17 | 18 | let package = Package( 19 | name: "Duration", 20 | products: [ 21 | // Products define the executables and libraries produced by a package, and make them visible to other packages. 22 | .library( 23 | name: "Duration", 24 | targets: ["Duration"]), 25 | ], 26 | dependencies: [ 27 | // Dependencies declare other packages that this package depends on. 28 | // .package(url: /* package url */, from: "1.0.0"), 29 | ], 30 | targets: [ 31 | // Targets are the basic building blocks of a package. A target can define a module or a test suite. 32 | // Targets can depend on other targets in this package, and on products in packages which this package depends on. 33 | .target( 34 | name: "Duration", 35 | dependencies: []), 36 | ] 37 | ) 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/SwiftStudies/Duration.svg?branch=master)](https://travis-ci.org/SwiftStudies/Duration) 2 | 3 | # Duration 4 | A simple Swift package for measuring and reporting the time taken for operations. It is derived from [a version for Playgrounds](http://www.swift-studies.com/blog/2015/5/21/performance-testing-in-xcode-playgrounds) that I blogged about some time ago, but kept needing to use in various projects. 5 | 6 | ## License 7 | Duration is distributed under the Apache 2.0 license 8 | 9 | ## Usage 10 | 11 | Duration supports iOS, OS X, tvOS, and Linux. 12 | 13 | ## Installation 14 | 15 | ### Install via the Swift Package Manager 16 | 17 | Add the following to your Package.swift 18 | ```swift 19 | .Package(url: "https://github.com/SwiftStudies/Duration.git", majorVersion: 1) 20 | ``` 21 | 22 | ### Simple Measurements 23 | 24 | There are two methods for simple timing measurements. You can insert calls before and after the section of code you wish to measure, for example 25 | ```swift 26 | Duration.startMeasurement("Tough Math") 27 | 28 | yourToughMathStuff() 29 | 30 | Duration.stopMeasurement() 31 | ``` 32 | Or you can use a block 33 | ```swift 34 | Duration.measure("Tough Math"){ 35 | yourToughMathStuff() 36 | } 37 | ``` 38 | Or even 39 | ```swift 40 | Duration.measure("Tough Math", block: yourToughMathStuff) 41 | ``` 42 | In all cases (by default) you will get the output (assuming it took 243 milliseconds) 43 | >Tough Math took: 243ms 44 | 45 | If measurements are nested, they will be appropriately indented in the output, for example if `yourToughMath()` made a measurement of part of its code you would see 46 | > 47 | Measuring Tough Math: 48 | Part 1 took: 100ms 49 | Part 2 took: 143ms 50 | Tough Math took: 243ms 51 | 52 | ### Understanding Performance Deviations 53 | 54 | In order to better understand how your code is impacted by other things the system is doing you can get average times and standard deviations for block based measurements by supplying a number of iterations for the block, so 55 | ```swift 56 | Duration.measure("Tough Math", iterations: 10, forBlock:myToughMath) 57 | ``` 58 | Would run the block 10 times, taking and reporting the 10 individual measurements and then the average time taken for the block, together with the standard deviation 59 | > 60 | Measuring Tough Math 61 | Iteration 1 took: 243ms 62 | Iteration 2 took: 242ms 63 | ... 64 | Iteration 10 took: 243ms 65 | Tough Math Average: 243ms 66 | Tough Math STD Dev.: 1ms 67 | 68 | ### Stopping Report Generation 69 | 70 | Because you may want to stop reporting of measurements in release builds, you can set the `logStyle` variable in order to control the logging behavior 71 | ```swift 72 | Duration.logStyle = .None 73 | ``` 74 | Will disable measurement logging. In the future I will extend this library to support logging to a data-structure for subsequent analysis, but at this point there are two valid values `.None` and `.Print` 75 | 76 | If you are using Duration within a Package of your own that you are distributing, rather than just over-writing the log style, you can push your desired style, then pop it to restore it to what a consuming package would want. For example 77 | ```swift 78 | public func myMethod(){ 79 | //Because this is a release of your package 80 | //don't log measurements 81 | pushLogStyle(.None) 82 | 83 | // Do stuff that is instrumented 84 | 85 | //Restore the logging style to whatever it was 86 | //before 87 | popLogStyle() 88 | } 89 | ``` 90 | # Reporting Issues 91 | Please report issues using GitHub's standard system 92 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .swiftpm 2 | # Created by https://www.gitignore.io/api/xcode,linux,macos,swift,swiftpm,windows,swiftpackagemanager 3 | # Edit at https://www.gitignore.io/?templates=xcode,linux,macos,swift,swiftpm,windows,swiftpackagemanager 4 | 5 | ### Linux ### 6 | *~ 7 | 8 | # temporary files which can be created if a process still has a handle open of a deleted file 9 | .fuse_hidden* 10 | 11 | # KDE directory preferences 12 | .directory 13 | 14 | # Linux trash folder which might appear on any partition or disk 15 | .Trash-* 16 | 17 | # .nfs files are created when an open file is removed but is still being accessed 18 | .nfs* 19 | 20 | ### macOS ### 21 | # General 22 | .DS_Store 23 | .AppleDouble 24 | .LSOverride 25 | 26 | # Icon must end with two \r 27 | Icon 28 | 29 | # Thumbnails 30 | ._* 31 | 32 | # Files that might appear in the root of a volume 33 | .DocumentRevisions-V100 34 | .fseventsd 35 | .Spotlight-V100 36 | .TemporaryItems 37 | .Trashes 38 | .VolumeIcon.icns 39 | .com.apple.timemachine.donotpresent 40 | 41 | # Directories potentially created on remote AFP share 42 | .AppleDB 43 | .AppleDesktop 44 | Network Trash Folder 45 | Temporary Items 46 | .apdisk 47 | 48 | ### Swift ### 49 | # Xcode 50 | # 51 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 52 | 53 | ## Build generated 54 | build/ 55 | DerivedData/ 56 | 57 | ## Various settings 58 | *.pbxuser 59 | !default.pbxuser 60 | *.mode1v3 61 | !default.mode1v3 62 | *.mode2v3 63 | !default.mode2v3 64 | *.perspectivev3 65 | !default.perspectivev3 66 | xcuserdata/ 67 | 68 | ## Other 69 | *.moved-aside 70 | *.xccheckout 71 | *.xcscmblueprint 72 | 73 | ## Obj-C/Swift specific 74 | *.hmap 75 | *.ipa 76 | *.dSYM.zip 77 | *.dSYM 78 | 79 | ## Playgrounds 80 | timeline.xctimeline 81 | playground.xcworkspace 82 | 83 | # Swift Package Manager 84 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 85 | # Packages/ 86 | # Package.pins 87 | # Package.resolved 88 | .build/ 89 | # Add this line if you want to avoid checking in Xcode SPM integration. 90 | # .swiftpm/xcode 91 | 92 | # CocoaPods 93 | # We recommend against adding the Pods directory to your .gitignore. However 94 | # you should judge for yourself, the pros and cons are mentioned at: 95 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 96 | # Pods/ 97 | # Add this line if you want to avoid checking in source code from the Xcode workspace 98 | # *.xcworkspace 99 | 100 | # Carthage 101 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 102 | # Carthage/Checkouts 103 | 104 | Carthage/Build 105 | 106 | # Accio dependency management 107 | Dependencies/ 108 | .accio/ 109 | 110 | # fastlane 111 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 112 | # screenshots whenever they are needed. 113 | # For more information about the recommended setup visit: 114 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 115 | 116 | fastlane/report.xml 117 | fastlane/Preview.html 118 | fastlane/screenshots/**/*.png 119 | fastlane/test_output 120 | 121 | # Code Injection 122 | # After new code Injection tools there's a generated folder /iOSInjectionProject 123 | # https://github.com/johnno1962/injectionforxcode 124 | 125 | iOSInjectionProject/ 126 | 127 | ### SwiftPackageManager ### 128 | Packages 129 | xcuserdata 130 | *.xcodeproj 131 | 132 | 133 | ### SwiftPM ### 134 | 135 | 136 | ### Windows ### 137 | # Windows thumbnail cache files 138 | Thumbs.db 139 | Thumbs.db:encryptable 140 | ehthumbs.db 141 | ehthumbs_vista.db 142 | 143 | # Dump file 144 | *.stackdump 145 | 146 | # Folder config file 147 | [Dd]esktop.ini 148 | 149 | # Recycle Bin used on file shares 150 | $RECYCLE.BIN/ 151 | 152 | # Windows Installer files 153 | *.cab 154 | *.msi 155 | *.msix 156 | *.msm 157 | *.msp 158 | 159 | # Windows shortcuts 160 | *.lnk 161 | 162 | ### Xcode ### 163 | # Xcode 164 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 165 | 166 | ## User settings 167 | 168 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 169 | 170 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 171 | 172 | ## Xcode Patch 173 | *.xcodeproj/* 174 | !*.xcodeproj/project.pbxproj 175 | !*.xcodeproj/xcshareddata/ 176 | !*.xcworkspace/contents.xcworkspacedata 177 | /*.gcno 178 | 179 | ### Xcode Patch ### 180 | **/xcshareddata/WorkspaceSettings.xcsettings 181 | 182 | # End of https://www.gitignore.io/api/xcode,linux,macos,swift,swiftpm,windows,swiftpackagemanager -------------------------------------------------------------------------------- /Sources/Duration/Duration.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2016 Swift Studies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | import Foundation 17 | 18 | /// Definition of a block that can be used for measurements 19 | public typealias MeasuredBlock = ()->() 20 | 21 | private var depth = 0 22 | 23 | private var depthIndent : String { 24 | return String(repeating: "\t", count: depth) 25 | } 26 | 27 | private var now : Double { 28 | return Date().timeIntervalSinceReferenceDate 29 | } 30 | 31 | /// Define different styles of reporting 32 | public enum MeasurementLogStyle{ 33 | /// Don't measure anything 34 | case none 35 | 36 | /// Log results of measurements to the console 37 | case print 38 | } 39 | 40 | /// Provides static methods for performing measurements 41 | public class Duration{ 42 | private static var timingStack = [(startTime:Double,name:String,reported:Bool)]() 43 | 44 | private static var logStyleStack = [MeasurementLogStyle]() 45 | 46 | /// When you are releasing and want to turn off logging, and your library 47 | /// may be used by another, it is better to push/pop a logging state. This 48 | /// will ensure your settings do not impact those of other modules. By pushing 49 | /// your desired log style, and sub-sequently pop'ing before returning from 50 | /// your measured method only your desired measuremets will be logged. 51 | public static func pushLogStyle(style: MeasurementLogStyle) { 52 | logStyleStack.append(logStyle) 53 | logStyle = style 54 | } 55 | 56 | /// Pops the last pushed logging style and restores the logging style to 57 | /// its previous style 58 | public static func popLogStyle(){ 59 | logStyle = logStyleStack.removeLast() 60 | } 61 | 62 | /// Set to control how measurements are reported. It is recommended to use 63 | /// `pushLogStyle` and `popLogStyle` if you intend to make your module 64 | /// available for others to use 65 | public static var logStyle = MeasurementLogStyle.print 66 | 67 | /// Ensures that if any parent measurement boundaries have not yet resulted 68 | /// in output that their headers are displayed 69 | private static func reportContaining() { 70 | if depth > 0 && logStyle == .print { 71 | for stackPointer in 0.. Double { 97 | return stopMeasurement(nil) 98 | } 99 | 100 | /// Prints a message, optionally with a time stamp (measured from the 101 | /// start of the current measurement. 102 | public static func log(message:String, includeTimeStamp:Bool = false) { 103 | reportContaining() 104 | 105 | if includeTimeStamp{ 106 | let currentTime = now 107 | 108 | let timeStamp = currentTime - timingStack[timingStack.count-1].startTime 109 | 110 | return print("\(depthIndent)\(message) \(timeStamp.milliSeconds)ms") 111 | } else { 112 | return print("\(depthIndent)\(message)") 113 | } 114 | } 115 | 116 | /// Stop measuring operations and generate log entry. 117 | public static func stopMeasurement(_ executionDetails: String?) -> Double { 118 | let endTime = now 119 | precondition(depth > 0, "Attempt to stop a measurement when none has been started") 120 | 121 | let beginning = timingStack.removeLast() 122 | 123 | depth -= 1 124 | 125 | let took = endTime - beginning.startTime 126 | 127 | if logStyle == .print { 128 | print("\(depthIndent)\(beginning.name) took: \(took.milliSeconds)" + (executionDetails == nil ? "" : " (\(executionDetails!))")) 129 | } 130 | 131 | return took 132 | } 133 | 134 | /// 135 | /// Calls a particular block measuring the time taken to complete the block. 136 | /// 137 | public static func measure(_ name: String, block: MeasuredBlock) -> Double { 138 | startMeasurement(name) 139 | block() 140 | return stopMeasurement() 141 | } 142 | 143 | /// 144 | /// Calls a particular block the specified number of times, returning the average 145 | /// number of seconds it took to complete the code. The time 146 | /// take for each iteration will be logged as well as the average time and 147 | /// standard deviation. 148 | public static func measure(name: String, iterations: Int = 10, forBlock block: MeasuredBlock) -> [String: Double] { 149 | precondition(iterations > 0, "Iterations must be a positive integer") 150 | 151 | var data: [String: Double] = [:] 152 | 153 | var total : Double = 0 154 | var samples = [Double]() 155 | 156 | if logStyle == .print { 157 | print("\(depthIndent)Measuring \(name)") 158 | } 159 | 160 | for i in 0..