[Swift通天遁地]七、数据与安全-(15)使用单元测试进行代码的性能分析

单元测试提供了一个测试性能的方法,可以用来对应用程序的执行性能进行检测。

本文将演示使用单元测试进行代码的性能分析:

两种不同的图片加载方式的性能差异,在【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 }

在性能报告窗口中,显示了基于时间维度的性能分析报告。

点击下方的数字可以查看样本峰值。

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10344023.html
今日推荐