1. 程式人生 > >[Swift通天遁地]七、數據與安全-(15)使用單元測試進行代碼的性能分析

[Swift通天遁地]七、數據與安全-(15)使用單元測試進行代碼的性能分析

修改 ets cat sts each code swift 顯示 called

單元測試提供了一個測試性能的方法,可以用來對應用程序的執行性能進行檢測。

本文將演示使用單元測試進行代碼的性能分析:

兩種不同的圖片加載方式的性能差異,在【Assets.xcassets】中導入圖片素材。

如果項目中沒有引用單元格測試框架,

項目導航區點擊選中項目名稱,再點擊中間列的【+】圖標進行添加。

在彈出的模板窗口中,選擇單元測試框架模板【iOS Unit Testing Bundle】

->【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 }

在性能報告窗口中,顯示了基於時間維度的性能分析報告。

點擊下方的數字可以查看樣本峰值。

[Swift通天遁地]七、數據與安全-(15)使用單元測試進行代碼的性能分析