IT박스

SourceKitService는 CPU를 소비하고 Xcode를 중지합니다.

itboxs 2020. 8. 19. 07:50
반응형

SourceKitService는 CPU를 소비하고 Xcode를 중지합니다.


이것은 베타 문제가 아닙니다. Xcode 6.0.1, 프로덕션 릴리스를 사용 중입니다. 내가 겪고있는 문제는 내가 작업중인 코드를 빌드하거나 실행하려고 할 때 Xcode가 오랜 시간 동안 응답하지 않고 SourceKitService가 CPU의 400 % 이상을 소비한다는 것입니다 (활동 모니터에 따르면). 이 문제는 지난 며칠 동안 새로운 것이지만, 이상하게도 9 월 17 일에 공식적으로 출시 된 이후 Xcode 6.0을 사용하고있었습니다.이 문제에 대한 수정 사항이 포함되기를 바라며 6.0.1로 업그레이드했습니다.

문제가 무엇인지에 대한 아이디어가 있습니까?


오늘 오후 초 Xcode 6.1.1 (베타가 아닌 공식 출시 버전)에서이 문제가 발생했습니다. 나는 Playground에서 몇 가지 코드를 실행하고 있었고 그 원인이 의심되었습니다. CPU는 거의 100 %로 고정되었고 Xcode는 빌드를 완료 할 수 없었습니다.

그래서 내가 한 일은 다음과 같습니다.

1. SourceKitService를 메인 CPU hog로 보여주는 "Activity Monitor"를 열었습니다.

2. "Activity Monitor"내에서 SourceKitService를 두 번 클릭하고 "Open Files and Ports"섹션을 클릭하면 / Users / myname / Library / Developer / Xcode / DerivedData / ModuleCache / 디렉터리 아래의 파일에서 작동하고 있음을 알 수 있습니다. 특정 폴더에 대해.

3. 지정된 폴더를 삭제했습니다 (명령 줄에서 rm -rf 사용). 캐시는 Xcode Derived 데이터 폴더의 내용을 안전하게 삭제할 수 있습니까?를 기준으로 재생성됩니다 . .

4. Activity Monitor를 다시 사용하여 SourceKitServer를 강제 종료합니다. Xcode 내에서 SourceKitService가 충돌했다는 너무 친숙한 표시를 보았습니다 (그래서 SourceKitService가 친숙하게 들리는 이유입니다!).

5. 3 단계를 반복합니다.

Mac은 다시 평화 롭습니다. 데이터가 손실되지 않았고 Xcode를 다시 시작할 필요도 없었습니다 (실패했습니다). 결론은 ModuleCache가 SourceKitService를 루프로 가져 오는 것 같고 폴더를 삭제하면 문제가 해결되는 것 같습니다. 이것이 당신에게도 효과가 있기를 바랍니다.

부트 노트 :

그건 그렇고, SourceKitService 문제의 원인은 Swift 클래스에 배열 선언이 너무 길기 때문입니다. 배열에 200 개가 넘는 항목이 있습니다. 30으로 줄였고 오류가 사라졌습니다. 따라서 문제는 사과 코드에서 일종의 스택 오버플로로 인해 발생했을 수 있습니다.


다음과 같은 약 60 개의 요소가있는 배열을 선언했기 때문에 문제가 발생했습니다.

let byteMap = [

["ECG" : (0,12)],
["PPG" : (12,3)],
["ECG" : (15,12)],
["PPG" : (27,3)],
["ECG" : (30,12)]

다음과 같이 유형에 명시 적으로 주석을 추가합니다.

let byteMap : [String: (Int, Int)] = [

["ECG" : (0,12)],
["PPG" : (12,3)],
["ECG" : (15,12)],
["PPG" : (27,3)],
["ECG" : (30,12)],

나는 그것을 멈출 수 있었다. 나는 그것이 긴 배열을 만날 때 루프로 들어가게 만드는 Swift의 유형 추론 및 유형 검사와 관련이 있다고 생각합니다.

이것은 Xcode 6.2에있었습니다. 또한 위에서 설명한대로 ModuleCache를 삭제했으며 이제 모든 것이 좋습니다.


이 문제는 실제 장치를 연결하고 시뮬레이터를 실행하지 않았을 때 10 번, 8 번 발생했습니다.

내 솔루션이 좋은지 확실하지 않지만 시뮬레이터와 실제 장치 간 전환으로 인해 문제가 발생했다고 생각합니다. 이상하게 들릴지 모르지만 캐시 파일 사이에 간섭을 일으키는 것처럼 보였습니다 .

내 문제를 해결 한 이유 :

  • 빌드 폴더 정리 : (Xcode에서)Alt + Shift + Command + K
  • 콘텐츠 및 설정 재설정 : (시뮬레이터에서) Command + Shift + K.
  • 평소보다 조금 더 오래 기다렸고 지속적인 클릭으로 Xcode 과부하

따라서 기본적으로 새 장치에서 실행하기 전에 캐시를 삭제하십시오.

편집하다

장치 연결없이 문제가 발생했습니다. Xcode를 종료하고 다시 열었을 때 문제가 사라졌습니다. 생각 에는 새 코드를 가져 오거나 병합 한 후 다시 색인화 문제가 될 수 있습니다.


SourceKitService가 최대 13GB의 메모리를 사용하는 또 다른 문제를 해결했습니다.

나는 String (많은 인수가있는 형식 줄 :

return String(format: "%d,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f", samples.count,sum1.x,sum1.y,sum1.z,sum1.rx,sum1.ry,sum1.rz,sum2.x,sum2.y,sum2.z,sum2.rx,sum2.ry,sum2.rz,sum3.x,sum3.y,sum3.z,sum3.rx,sum3.ry,sum3.rz)

이것으로 교체하면 잘 작동했습니다 (메모리 축적 및 정상적인 CPU 소비 없음)

    var output: String = ""

    output += String(format: "%d,", samples.count)
    output += String(format: "%.3f,%.3f,%.3f,", sum1.x, sum1.y, sum1.z)
    output += String(format: "%.3f,%.3f,%.3f,", sum1.rx, sum1.ry, sum1.rz)
    output += String(format: "%.3f,%.3f,%.3f,", sum2.x, sum2.y, sum2.z)
    output += String(format: "%.3f,%.3f,%.3f,", sum2.rx, sum2.ry, sum2.rz)
    output += String(format: "%.3f,%.3f,%.3f,", sum3.x, sum3.y, sum3.z)
    output += String(format: "%.3f,%.3f,%.3f", sum3.rx, sum3.ry, sum3.rz)

    return output

나는 Xcode 9 에서이 문제를 겪고 있으며 여러 솔루션을 탐색했습니다. 나를 위해 소스 제어를 비활성화 하는 것이 트릭을 수행하는 것처럼 보였습니다.

Xcode -> Preferences -> Source Control -> uncheck "Enable Source Control"

이것이 작동하지 않으면 터미널 에서 renice 명령을 사용하는 것이 좋습니다 . 여기에 더 자세히

소스 제어 비활성화

시도했지만 도움이되지 않은 다른 단계 :

  1. Xcode 닫기-> 파생 데이터 삭제
  2. 사이클링 머신
  3. "깨끗한"프로젝트

나를 위해 그것은 파생 데이터를 삭제하기 위해 노력했습니다. 메뉴에서 '제품'을 선택하고 Alt 키를 누른 상태에서 '빌드 폴더 정리'를 선택하십시오. 단축키 : Alt + Shift + Command + K


내 프로젝트의 긴 편집에서 문제를 파악하는 데 4 시간을 소비합니다. 첫 번째 시도는 컴파일하는 데 42 분이 걸립니다.

/Users/myname/Library/Developer/Xcode/DerivedData/ModuleCache/다시 시작한 후 @LNI에서 제안한대로 모든 캐시를 지우고 SourceKitService코드에 몇 가지 변경 사항을 적용합니다.

1)

    var initDictionary:[String:AnyObject] = [
                    "details" : "",
                    "duration" : serviceDuration,
                    "name" : serviceName,
                    "price" : servicePrice,
                    "typeId" : typeID,
                    "typeName" : typeName,
                    "url" : "",
                    "serviceId" : serviceID,
                    "imageName" : ""
                ]

에서

    var initDictionary= [
                    "details" : "",
                    "duration" : serviceDuration,
                    "name" : serviceName,
                    "price" : servicePrice,
                    "typeId" : typeID,
                    "typeName" : typeName,
                    "url" : "",
                    "serviceId" : serviceID,
                    "imageName: "" ]

2)

            if let elem = obj.property,
                let elem2 = obj.prop2,
                etc
                 {
                 // do stuf here
            }

에서

           let value1 = obj.property ?? defaultValue

삼)

           let serviceImages = images.filter { $0.serviceId == service.id }
           let sorted = serviceImages.sort { $0.sort > $1.sort }

에서

            let serviceImages = images.filter { $0.serviceId == service.id }. sort { $0.sort > $1.sort }

결과적으로 컴파일 시간-3 분, 그렇게 빠르지는 않지만 42 분 동안 더 좋습니다.

결과적으로 이전 SourceKitService-~ 5,2Gb의 메모리와 ~ 0.37Gb 이후

여기에 이미지 설명 입력


데이터 유형을 지정하지 않거나 [String : Any]를 사용하여 신속하게 사전을 생성하지 마십시오.

'Any'유형을 사용하면 컴파일러가 데이터 유형을 확인하기 위해 무한 루프를 실행할 수 있습니다.

컴파일 오류가 발생하지 않으며 'swift'및 'SourceKitService'라는 작업에 대해 많은 메모리를 확보하여 '빠른 소스 파일 컴파일'시 Mac이 정지됩니다.


나는 그러한 문제에 직면했습니다. 소스 키트 서비스는 10GB 사용량을 사용했습니다. 활동 모니터의 신속한 프로세스는 6GB 이상의 사용량에 도달합니다. 다음 코드를 사용했습니다.

var details : [문자열 : 모두] = [ "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10, "11": 11, "12": 12, "13": 13, "14": 14, "15": 15, "16": 16]

이 문제를 해결하기 위해 코드를 다음과 같이 변경했습니다.

var 세부 정보 : [문자열 : 모두] = [:]

세부 정보 [ "1"] = 1

세부 정보 [ "2"] = 2

세부 정보 [ "3"] = 3

세부 정보 [ "4"] = 4

세부 정보 [ "5"] = 5

세부 정보 [ "6"] = 6

세부 정보 [ "7"] = 7

세부 정보 [ "8"] = 8

세부 정보 [ "9"] = 9

세부 정보 [ "10"] = 10

세부 정보 [ "11"] = 11

세부 정보 [ "12"] = 12

세부 정보 [ "13"] = 13

세부 정보 [ "14"] = 14

세부 정보 [ "15"] = 15

세부 정보 [ "16"] = 16


같은 문제에 직면 Xcode 7.2 (7C68)

해결책은 제 클래스가 정의에있는 프로토콜의 메서드를 구현하는 것이 었습니다.


  1. Xcode 종료
  2. 터미널에서 실행 :

rm -rf ~/Library/Developer/Xcode/DerivedData/ModuleCache/*


LNI의 허용 답변과 다음 답변의 차이점에 유의하십시오.

  1. 충돌하는 것보다 충돌하지 않는 것이 항상 낫습니다. 특히 Xcode 프로세스 / 구성 요소와 관련하여.
  2. 저는 Apple 개발자는 아니지만 캐시를 부분적으로 삭제하면 무결성이 손상 될 수 있습니다. 모든 캐시를 정리 한 후 상당한 지연이 발생하지 않았습니다.

이것은 xcode 버전 7.3.1 (7D1014)에서 여전히 문제입니다. LNI가 지적한 것처럼 실제로는 너무 길지 않은 너무 긴 배열이었습니다. 배열을 다음과 같이 다양한 배열로 분할하여 문제를 해결했습니다.

let firstLevel = [
            [1, 0, 1, 0, 1],
            [0, 0, 0, 0, 0],
            [1, 0, 1, 0, 1],
            [0, 0, 0, 0, 0],
            [1, 0, 1, 0, 1],
            [0, 0, 0, 0, 0]
        ]
        let secondLevel = [
            [0, 0, 0, 0, 0],
            [0, 1, 0, 1, 0],
            [0, 0, 0, 0, 0],
            [0, 1, 0, 1, 0],
            [0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0]
        ]
        let thirdLevel =     [
            [0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0],
            [0, 0, 1, 0, 0],
            [0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0]
        ]
        let map = [firstLevel, secondLevel, thirdLevel]

XCode 8.2.1 (8C1002) 및 다음 코드에서 동일한 문제가 발생했습니다.

import UIKit
import AVFoundation
import Photos
import CoreMotion
import Foundation


class TestViewController: UIViewController
{
    let movieFileOutput = AVCaptureMovieFileOutput()


var anz_total_frames = 0, anz_total_miss = 0

@IBOutlet weak var tfStatistics: UITextView!


func showVideoStatistics()
{
    let statisticText:String =             "frames: \(self.anz_total_frames)" + String.newLine +

        "frames/s: \(self.anz_total_frames / self.movieFileOutput.recordedDuration.seconds)" + String.newLine +

        "miss: " + formatText4FramesPercent(self.anz_total_miss) + String.newLine +
    "nicht erkannt: " + formatText4FramesPercent(self.anz_total_miss) + String.newLine +
        "nicht erkannt: " + formatText4FramesPercent(self.anz_total_miss) + String.newLine +
        "nicht erkannt: " + formatText4FramesPercent(self.anz_total_miss) + String.newLine +
        "nicht erkannt: " + formatText4FramesPercent(self.anz_total_miss) + String.newLine +
        "nicht erkannt: " + formatText4FramesPercent(self.anz_total_miss) + String.newLine +
        "nicht erkannt: " + formatText4FramesPercent(self.anz_total_miss) + String.newLine +
        "nicht erkannt: " + formatText4FramesPercent(self.anz_total_miss) + String.newLine +
        "nicht erkannt: " + formatText4FramesPercent(self.anz_total_miss) + String.newLine +
        "nicht erkannt: " + formatText4FramesPercent(self.anz_total_miss) + String.newLine +
        "nicht erkannt: " + formatText4FramesPercent(self.anz_total_miss) + String.newLine


    self.tfStatistics.text = statisticText
}

func formatText4FramesPercent(_ anz:Int) -> String
    {
        let perc = Double(anz)*100.0/Double(anz_total_frames)
        return String(perc.format(".1") + "%")
    }
}

및 이러한 확장 :

extension String {
    var localized: String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
    }

    static var newLine: String {
        return "\r\n"
    }
}

extension Int {
    func format(_ f: String) -> String {
        return String(format: "%\(f)d", self)
    }
}

extension Double {
    func format(_ f: String) -> String {
        return String(format: "%\(f)f", self)
    }
}

TestViewController에서이 줄을 주석 처리하여 해결했습니다.

        "frames/s: \(self.anz_total_frames / self.movieFileOutput.recordedDuration.seconds)" + String.newLine +

Took me more than an hour to find it, I hope a can save some time of somebody else. I filed a bug report to Apple with number 30103533


I was facing the same problem after migrating the project to swift 3, find out solution it was taking time because of dictionaries and array created without data type.


This behavior appeared in my project when I accidentally declared a class that inherited from itself. Xcode 8.2.1, using Swift 3.


I also had this issue, in my case I was declaring a big array like this:

var myArray: [(String, Bool?)]?
myArray = [("someString", someBool),
("someString", someBool),
("someString", someBool),
("someString", someBool),
("someString", someBool)
.
.
("someString", someBool)]

I solved the problem by adding the items 1 per line instead of all at the same time:

var myArray = [(String, Bool?)]()
myArray.append(("someString", someBool))
myArray.append(("someString", someBool))
myArray.append(("someString", someBool))
myArray.append(("someString", someBool))
myArray.append(("someString", someBool))
.
.
.

this fixed the problem.


For Objective-C projects:

I had the same problem, and there's zero Swift code in our project, so it wasn't the type inference checker.

I tried every other solution here and nothing worked - what FINALLY fixed it for me was rebooting the computer in recovery mode and running the disk repair. I can finally work in peace again!

I'm guessing that it happened because of some broken symlinks, probably pointing towards each other and making the service run around in an endless loop.


I'm having a similar issue with Xcode 8.2.1 - with a section of 1,000+ lines of code commented-out via /* */. Commenting-out the section caused the issue, and removing the commented-out code fixed it.


I had the same problem with SourceKitService.

I solved. NEVER ADD SUBVIEWS WITH FOR LOOP.

To detect issue I use: https://github.com/RobertGummesson/BuildTimeAnalyzer-for-Xcode


I ran into something similar combining multiple ?? operators to provide a default for optional string values.

I was experimenting with the debug code below when the fan on my trusty mid-2010 MacBook Pro began running hard. SourceKitService was sucking up every CPU cycle it could get. Commenting and uncommenting the offending line made it very clear what SourceKitService was choking on. It looks like using more than one ?? operator to provide a default is an issue on an old machine. The work around is just don't do it. Break it up into multiple assignments which makes some ugly debug code even uglier.

placeMark is an instance of CLPlacemark. The properties used here return optional strings.

I was using Xcode Version 8.3.2 (8E2002) running on OS 10.12.4 (16E195)

// one term is not an issue
let debugString1 = (placeMark.locality ?? "")

// two terms pushes SourceKitService CPU use to 107% for about 60 seconds then settles to 0%
let debugString1 = (placeMark.locality ?? "")  + ", " +  (placeMark.administrativeArea ?? "") 

// three terms pushes SourceKitService CPU use to 187% indefinitely 
let debugString1 = (placeMark.locality ?? "")  + ", " +  (placeMark.administrativeArea ?? "")  + (placeMark.postalCode ?? "")

// ugly but it's safe to use
var debugString1 = placeMark.locality ?? ""
debugString1 = debugString1 + ", " +  (placeMark.administrativeArea ?? "")
debugString1 = debugString1 + " " + (placeMark.postalCode ?? "")

Converting long Arrays to Functions seem to resolve the problem for me:

var color: [UIColor] {
    return [
        UIColor(...),
        UIColor(...),
        ...
    ]
}

to:

func color() -> [UIColor] {
    return [
        UIColor(...),
        UIColor(...),
        ...
    ]
}

run in terminal:

killall Xcode
rm -rf ~/Library/Developer/Xcode/DerivedData/ModuleCache
open /Applications/Xcode.app

you could also create a terminal command using this alias:

echo alias xcodeFix='killall Xcode;rm -rf ~/Library/Developer/Xcode/DerivedData/ModuleCache;open /Applications/Xcode.app' >> ~/.profile
source ~/.profile

and then just run

xcodeFix

XCode 10.0에서 여전히 문제가 발생합니다. 소스 제어 옵션에서 "소스 제어 변경 사항 표시"를 비활성화하여 문제를 해결할 수 있습니다.

여기에 이미지 설명 입력


https://www.logcg.com/en/archives/2209.html

SourceKitService는 Swift의 유형 추론 작업을 담당했습니다.

private lazy var emojiFace = ["?", "?", "?", "?"]

명시 적으로 입력하도록 변경

private lazy var emojiFace:[String] = ["?", "?", "?", "?"]

SourceKitService CPU 사용량이 즉시 감소합니다.

참고 URL : https://stackoverflow.com/questions/26151954/sourcekitservice-consumes-cpu-and-grinds-xcode-to-a-halt

반응형