首页 > 其他分享 >使用 Swift 代码优化项目编译速度

使用 Swift 代码优化项目编译速度

时间:2024-01-19 16:57:56浏览次数:33  
标签:Xcode time 编译 代码优化 let 克魔 Swift

引言

软件的性能是评价一个软件质量的重要指标,尤其在今天这个时代,性能已成为大型项目不可或缺的考虑因素之一。对于用户量极大的软件,如网银系统、在线购物商城等,更是必须保证其高效稳定的性能。在这种背景下,优化项目的编译速度就显得尤为重要。本文将介绍如何使用 Swift 代码优化项目编译速度。

找出编译耗时过长的文件

要优化项目的编译速度,首先需要把耗时过长的文件找出来,然后进行重点优化。这里会用到 Xcode build 的两个OTHER_SWIFT_FLAGS:

  • -Xfrontend:如果编译或类型检查时耗时多长,则在 Xcode 中输出警告。

  • -debug-time-function-bodies:输出每个函数的编译时长。

添加这些 flag 的方法为:

  1. 选中 Target

  2. 选中 Build Settings

  3. 搜索 “Other Swift Flags”

  4. 添加 -Xfrontend -debug-time-function-bodies

基于这两个 flag,有 3 个方法可以找到耗时过长的文件:

方法一:使用克魔助手

克魔助手是一款专为苹果手机 iOS 应用开发设计的辅助工具,提供了丰富的性能监控功能,帮助开发者优化应用的性能。以下是使用克魔助手找到编译耗时过长的文件的步骤:

  1. 下载克魔助手:用户可以前往克魔助手工具官网进行免费下载,该工具提供绿色软件版本,无需其他安装流程。下载后解压即可开始使用。下载地址是 https://www.keymob.com 。

在这里插入图片描述

 

  1. 注册和登录:为了使用克魔助手工具,用户需要在电脑上安装并登录该工具。在登录后,用户可以继续其他操作流程。克魔开发助手提供了简单的登录码获取流程,确保用户能够方便地使用该工具。

 

在这里插入图片描述

 

2.选择文件管理界面并开始监听:双击克魔开发助手.exe 启动克魔助手后,点击右上角的登录按钮,输入邮箱后,没登录码的点击获取登录码,有的可以直接输入登录码,登录成功后,选择文件管理界面。然后自定义选择列,并点击 “开始监听” 来查看应用程序的性能情况。

在这里插入图片描述

 

方法二:使用 Xcode 控制台

在 Xcode 的控制台中输入以下命令即可输出时间最久的前 10 个文件:

find . -type f -name '*.swift' -exec \
  sh -c "echo '{}' && swiftc -v -c '{}' 2>&1 | awk '/^.{10}[ ]+[0-9\.]+ms/{print \$0}' | sort -rn | head -10" \;

方法三:使用 Xcode 插件

使用 Xcode 插件 SwiftLint 可以自动输出编译耗时最长的文件。安装方法如下:

  1. 打开 Terminal,输入以下命令:

brew install swiftlint
  1. 在 Xcode 中打开 Preferences(快捷键 Command + ,),选择 Text Editing,然后选择 Code completion。

  2. 在 Code completion 下面的 Fuzzy matching 一栏中,勾选 Show snippets using: 和 Swift。然后再选择 Edit All-in-One Snippet…。

  3. 进入 Snippet 编辑页面,复制以下代码并保存:

// MARK: - Performance Metrics

// Prints the compile time of each function or method in this file.
// Add to the `OTHER_SWIFT_FLAGS` build setting for the target.
// -Xfrontend -debug-time-function-bodies
//
// For more information about how to use debug-time-function-bodies see:
// - https://pspdfkit.com/blog/2018/how-to-reduce-swift-compile-times/
// - https://github.com/apple/swift/pull/13132#issuecomment-312358040
// - WWDC 2018 session 404 Optimizing Swift build times
// - https://youtu.be/nJwVabxL5Gw?t=11m16s
//
// If you add this to a Swift file, it will print the compile time of each
// method in this file to the console on build.
//
// Usage:
// In Xcode 9.x and later:
// 1. Open your project
// 2. Go to the Build Phases tab of your app's target
// 3. Click the + button in the top left and select "New Run Script Phase"
// 4. Add the following code to the script area below the shell:
//      "${PODS_ROOT}/SwiftLint/swiftlint" --no-cache --config "${PODS_ROOT}/SwiftLint/.swiftlint.yml"
//      "${PROJECT_DIR}/Scripts/perf.swift"
//    Note: You may need to customise the paths to suit your project structure.
// 5. Drag the new run script phase to be just before the "Compile Swift Sources"
//    phase in the list.
// 6. Rebuild your project (Command-B)
// 7. The compile time for each function in each source file will now be logged
//    to the console, sorted by longest compile time first.

import Foundation

let numBitsInByte = 8

extension Double {
    func rounded(toPlaces places: Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}

extension String {
    func padding(toLength length: Int, withPad padCharacter: Character) -> String {
        let padding = String(repeatElement(padCharacter, count: max(0, length - count)))
        return self + padding
    }
}

func readableTime(_ time: Double) -> String {
    if time < 0.001 {
        return "< 0.001ms"
    } else if time < 1 {
        return "\(time.rounded(toPlaces: 3))ms"
    } else {
        var timeStr = "\(time.rounded(toPlaces: 2))s"
        if time > 60 {
            let minutes = Int(time / 60)
            let seconds = time.truncatingRemainder(dividingBy: 60)
            timeStr = "\(minutes)m \(seconds.rounded(toPlaces: 2))s"
        }
        return timeStr.padding(toLength: 10, withPad: " ")
    }
}

func measure<A>(name: String, _ f: () -> A) -> A {
    let start = DispatchTime.now()
    let result = f()
    let end = DispatchTime.now()
    let time = Double(end.uptimeNanoseconds - start.uptimeNanoseconds) / Double(numBitsInByte * 1000000)
    print("\(readableTime(time)): \(name)")
    return result
}

  1. 在 Xcode 的 Build Phases 中添加一个 Run Script,将以下代码复制到 Run Script 中:

"${PODS_ROOT}/SwiftLint/swiftlint" --no-cache --config "${PODS_ROOT}/SwiftLint/.swiftlint.yml"
"${SRCROOT}/Scripts/perf.swift"

总结

优化项目的编译速度是一个不断迭代的过程,需要不断地寻找和解决问题。本文介绍了如何使用 Swift 代码来找出编译耗时过长的文件,并介绍了三种方法:使用克魔助手、使用 Xcode 控制台和使用 Xcode 插件 SwiftLint。希望这些方法能够帮助读者优化项目的编译速度。

参考资料

标签:Xcode,time,编译,代码优化,let,克魔,Swift
From: https://www.cnblogs.com/sdges/p/17975037

相关文章

  • Jax框架:通过显存分析判断操作是否进行jit编译
    相关:https://jax.readthedocs.io/en/latest/device_memory_profiling.html代码:importjaximportjax.numpyasjnpimportjax.profilerdeffunc1(x):returnjnp.tile(x,10)*0.5deffunc2(x):y=func1(x)returny,jnp.tile(x,10)+1x=jax.random.......
  • android开发编译出错:Unable to find method ''org.gradle.api.file.RegularFileProper
    Unabletofindmethod''org.gradle.api.file.RegularFilePropertyorg.gradle.api.file.ProjectLayout.fileProperty(org.gradle.api.provider.Provider)'''org.gradle.api.file.RegularFilePropertyorg.gradle.api.file.ProjectLayout.fileProp......
  • Swift抓取某网站律师内容并做排名筛选
    有个很要好的朋友,今天找我说他的朋友欠他钱,因为工程上面的事情,所以一直没拿到款。想让我找个靠谱的律师帮他打官司,因为这个也不是我的强项,也没有这方面的经验。随即从律师网站爬取对应律师口碑以及成功案例,然后把资料交到他手里让他自己选择。这个任务需要使用Swift和网络爬虫库,......
  • Golang静态类型、编译型的语言学习
    golang属于一种静态类型、编译型的语言,它的设计目标是提供一种简单、高效、可靠的编程语言,适用于构建大型软件系统。Go语言的设计哲学是简洁、直接、易于理解和使用,Go语言支持并发编程,引入了goroutine和channel的概念,使得并发编程更加简单和高效,无论是用于Web开发、服务器编程、......
  • ubuntu编译opencv:cmake时下载超时及找不到源的问题
    1ade下载超时查看CMakeDownlodLog.txt找下载地址和目标路径(包含md5值),按下载地址下载文件,放到你的opencv-4.7.0/.cache/ade下,记得把文件改名改成包含md5值的。其他缺失文件也可以一样处理。2即使下载完依然cmake报错--ConfiguringdoneCMakeErroratmodules/gapi/cmake/Do......
  • idea 项目编译内存溢出解决配置
    https://blog.csdn.net/malin970824/article/details/89843478 以下几种方式都可尝试下:1.在idea安装的bin目录修改配置文件 -Xms512m-Xmx2024m-Xss4M-XX:MaxPermSize=2024m 2.修改settings 3.修改tomcat-server-Xms512m-Xmx2024m-Xss4M-XX:PermSize=512M-XX:......
  • 极智一周 | 谈谈AI发展、训练算力、推理算力、AI编译框架、Copilot键 And so on
    欢迎关注我的公众号[极智视界],获取我的更多技术分享大家好,我是极智视界,带来本周的[极智一周],关键词:谈谈AI发展、训练算力、推理算力、AI编译框架、Copilot键Andsoon。极智视界本周热点文章回顾(1)谈谈AI发展系列本周带来三篇"谈谈AI发展"分享,包括AI训练算力、AI推理......
  • docker 创建编译容器 rk3588
    创建ubuntu指定名称创建容器dockerrun-t-i-d-v/opt:/opt--nameubuntu2004ubuntu:20.04/bin/bash修改ustc镜像源sed-i's@//.*archive.ubuntu.com@//mirrors.ustc.edu.cn@g'/etc/apt/sources.listsed-i's/security.ubuntu.com/mirrors.ustc.edu.cn/g'......
  • 大师学SwiftUI第6章 - 声明式用户界面 Part 4
    步进器视图Stepper视图创建一个带递增和递减按钮的控件。该结构体提供了多个初始化方法,包含不同的配置参数组合。以下是最常用的一部分。Stepper(String,value:Binding,in:Range,step:Float,onEditingChanged:Closure):此初始化方法创建一个Stepper视图。第一个参数定义标签......
  • 编译openwrt分支immortalwrt小结
    编译环境:ubuntu20.04LTS,确保能连接github获取必须依赖:sudoaptupdate-ysudoaptfull-upgrade-ysudoaptinstall-yackantlr3asciidocautoconfautomakeautopointbinutilsbisonbuild-essential\bzip2ccacheclangcmakecpiocurldevice-tree-compilere......