├── .gitignore ├── .travis.yml ├── LICENSE ├── Package.swift ├── README.md ├── Sources └── Duration │ └── Duration.swift └── Tests ├── DurationTests ├── DurationTests.swift └── XCTestManifests.swift └── LinuxMain.swift /.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 -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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.. [XCTestCaseEntry] { 5 | return [ 6 | testCase(DurationTests.allTests), 7 | ] 8 | } 9 | #endif 10 | -------------------------------------------------------------------------------- /Tests/LinuxMain.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | 3 | import DurationTests 4 | 5 | var tests = [XCTestCaseEntry]() 6 | tests += DurationTests.allTests() 7 | XCTMain(tests) 8 | --------------------------------------------------------------------------------