[Swift通天遁地]七、数据与安全-(15)使用单元测试进行代码的性能分析
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10344023.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
单元测试提供了一个测试性能的方法,可以用来对应用程序的执行性能进行检测。
本文将演示使用单元测试进行代码的性能分析:
两种不同的图片加载方式的性能差异,在【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 }
在性能报告窗口中,显示了基于时间维度的性能分析报告。
点击下方的数字可以查看样本峰值。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)