★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-foyuumgq-mb.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
目錄:[Swift]通天遁地Swiftgit
單元測試提供了一個測試性能的方法,能夠用來對應用程序的執行性能進行檢測。github
本文將演示使用單元測試進行代碼的性能分析:安全
兩種不一樣的圖片加載方式的性能差別,在【Assets.xcassets】中導入圖片素材。微信
若是項目中沒有引用單元格測試框架,框架
項目導航區點擊選中項目名稱,再點擊中間列的【+】圖標進行添加。ide
在彈出的模板窗口中,選擇單元測試框架模板【iOS Unit Testing Bundle】post
->【Next】->保持默認的選項設置->【Finish】性能
打開單元測試用例文件【UnitTestProject_DemoTests.Swift】單元測試
1 import XCTest 2 @testable import UnitTestProject_Performance 3 4 class UnitTestProject_PerformanceTests: XCTestCase { 5 6 override func setUp() { 7 super.setUp() 8 // Put setup code here. This method is called before the invocation of each test method in the class. 9 } 10 11 override func tearDown() { 12 // Put teardown code here. This method is called after the invocation of each test method in the class. 13 super.tearDown() 14 } 15 16 func testExample() { 17 // This is an example of a functional test case. 18 // Use XCTAssert and related functions to verify your tests produce the correct results. 19 } 20 21 //在性能測試示例方法中。讀取項目中的圖片素材。 22 //點擊方法名稱左側的菱形圖標,執行測試用例。 23 func testPerformanceExample() { 24 // This is an example of a performance test case. 25 self.measure { 26 // Put the code you want to measure the time of here. 27 //建立一個601次的循環語句,重複執行圖片加載的動做。 28 //0.038s 29 for _ in 0 ... 600 30 { 31 //使用圖像類的名稱初始化方法,經過指定圖片的名稱, 32 //從項目中加載指定的圖片 33 let image = UIImage(named: "Picture") 34 print(image?.size ?? CGSize(width: 0, height: 0)) 35 //點擊左側的菱形圖標,打開性能報告窗口。 36 } 37 38 //修改圖片的加載方式:0.069秒 39 for _ in 0 ... 600 40 { 41 //使用圖像類的另外一種初始化方法,經過指定圖片的名稱, 42 //從項目中加載指定的圖片 43 let image = UIImage(contentsOfFile: "Picture") 44 print(image?.size ?? CGSize(width: 0, height: 0)) 45 //點擊左側的菱形圖標,打開性能報告窗口。 46 } 47 } 48 } 49 }
在性能報告窗口中,顯示了基於時間維度的性能分析報告。
點擊下方的數字能夠查看樣本峯值。