Program Club

transformClassesWithDexForDebug에서 Gradle 빌드가 느립니다.

proclub 2020. 11. 18. 21:43
반응형

transformClassesWithDexForDebug에서 Gradle 빌드가 느립니다.


내 Android 앱을 빌드하는 데는 약 90 초 ( "빠름" )가 걸리며 코드를 업데이트 할 때마다 최대 3 분이 걸립니다. 그것은 정말로 시간 낭비이며 해결책이 도달해야한다고 생각합니다. 나는 문제를 조사하려고 시도했고 제안과 함께 다른 블로그 게시물과 SO 답변을 찾았으며 대부분 시도했습니다.

  • org.gradle.deamon = true 인 gradle.properties 파일이 있습니다.
  • 오프라인 작업을 수행하기 위해 Gradle Prefence로 Android Studio에서 실행합니다 (개선되었지만 여전히 느림).
  • 명령 줄에서 실행합니다 (더 빠르지 만 여전히 느립니다).
  • build.gradle, defaultConfig에서 multiDexEnabled를 false로 설정했습니다.
  • build.gradle, dexOptions에서 preDexLibraries를 false로 설정했습니다.
  • gradle-wrapper.properties에서 최신 gradle 버전 (2.8)을 가져옵니다 (2.4에서 상당한 속도 변경이 발생했습니다)

전체 빌드 시간의 약 85 %가 오래 걸리는 것처럼 보이는 프로세스는 다음과 같습니다 . : app : transformClassesWithDexForDebug

그 과정은 실제로 무엇을하고 있습니까? 충돌이 발생한 사람들을 찾을 수 있지만 시간이 많이 걸리는 점을 제외하고는 잘 작동합니다. 이 시점에서 Dex가 실제로 필요하지 않기 때문에 필요합니까?

또한 13 개의 종속성과 3 개의 testCompile 종속성이 있습니다. 나는 이미 특정 플레이 패키지를 가리 키기 때문에 필요하지 않은 것은 컴파일하지 않습니다. 내가 일을 올바르게 이해하면 gradle은 각 프로젝트가 빌드하는 모든 라이브러리를 빌드합니다. 그것이 맞다면 건너 뛸 수있는 방법이 있습니까? 랩업 라이브러리로 직접 빌드하고 매번 처리 할 필요없이 포함 할 수 있습니까? 이로 인해 향후 종속성 변경에 대한 유연성을 잃을 수 있지만이 시점에서 gradle을 기다리는 동안 하루에 한 시간 이상 쉽게 잃는 것 같습니다. 유연성이 나에게 그만한 가치가 있는지 잘 모르겠습니다.

빌드 프로세스를 개선 할 수있는 방법에 대한 조언을 기대하고 있습니다. 미리 감사드립니다.


Android Studio 2.1 및 Android Gradle 플러그인 v2.1.0으로 업그레이드하면이 문제가 대부분 해결되었습니다. 업데이트 된 IDE를 설치 한 후 Gradle 플러그인도 업데이트하라는 메시지가 표시됩니다. 루트 build.gradle 파일에 다음 행이있는 경우 올바른 버전이 있음을 알 수 있습니다.

classpath 'com.android.tools.build:gradle:2.1.0'

중요 : 업그레이드 외에도 Gradle 데몬에 할당 된 메모리 양을 2048mb로 늘려야이 값 비싼 덱싱 단계를 처리 할 수 ​​있습니다. 이렇게하려면 루트 gradle.properties 파일에 다음을 추가합니다.

org.gradle.jvmargs = -Xmx2048m

위의 질문에서 경험 한 것과 비슷하게 빌드 시간이 느 렸지만 업그레이드 후 빌드 속도가 크게 증가했습니다. 자세한 내용은 여기에서 Android Gradle 플러그인 v2.1.0의 출시 노트를 참조하세요.

http://developer.android.com/tools/revisions/gradle-plugin.html


편집 :이 시점에서 1.5 설치와 함께 Android Studio 2.x를 실행하는 것이 좋습니다. 업데이트 된 모든 도구뿐만 아니라 실제로 도움이되는 즉시 실행에 액세스 할 수 있습니다. 1.5에 머물고 있다면 계속 읽으십시오 ...

Android Studio 1.5 디버그 빌드 속도를 2 분에서 30 초로 늘 렸습니다. 이것은 명령 줄 실행에서 작동하지 않을 수 있지만 더 빠를 수 있습니다.

이 구성을 사용하면 첫 번째 IDE 빌드 에 동일한 시간 이 걸리지 만 클래스를 수정하더라도 증분 빌드가 더 빠릅니다 . 연결된 라이브러리를 수정하면 약간의 이득을 잃게됩니다.

1 단계. (이미> = 21의 minSdkVersion을 대상으로 할만큼 운이 좋다면 건너 뛰십시오.)

@vanomart의 minSdkVersion 디버그 풍미가> = 21 인 대답은 틀린 것은 아니지만 필요한 유일한 부분은 모듈 (앱) build.gradle에 다음을 추가하고 빌드 변형 탭에서 디버깅하는 동안 개발자를 대상으로 지정하는 것입니다.

android {
    [...]
    productFlavors {
        dev {
            minSdkVersion 21 //The important bit.
        }
        prod {
            minSdkVersion 15 //Example. Set to your real requirement.
        }
    }

2 단계. 증분 빌드 및 pre-dexing libs.

당신의에서 모듈 (응용 프로그램) build.gradle는 다음과 같은 설정을 설정합니다. 이것은 모든 빌드를 처음부터 시작하는 빌더 서버가 아니라 IDE 빌드의 경우 더 빠릅니다.

android {
    [...]
    dexOptions {
        preDexLibraries true
        javaMaxHeapSize "2g" // Use gig increments depending on needs
        incremental true
    }

소스, "빌드 서버 성능 향상"의 (일부) 역행 : http://tools.android.com/tech-docs/new-build-system/tips#TOC-Improving-Build-Server-performance

3 단계 . 모듈 (앱) build.gradle 에서 최신 buildToolsVersion을 사용하고 있는지 확인합니다 .

android {
    buildToolsVersion "23.0.2"
    [...]

"... 모든 모듈의 빌드 도구 버전을 최신 (23.0.2)으로 업데이트합니다. [...] 빠른 새 버전의 dex를 사용하여 즉시 실행 및 전체 빌드가 조금 더 빨라집니다. . "

출처 : http://tools.android.com/tech-docs/instant-run

4 단계. 최신 Gradle 빌드 도구 사용

당신의에서 프로젝트 build.gradle , 최신 (현재 2.0.0-alpha6)로 설정

buildscript {
    dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0-alpha6'

업데이트 목록 : http://tools.android.com/tech-docs/new-build-system

5 단계. 최신 Gradle 래퍼를 사용합니다. gradle-wrapper.properties를 수정하고 2.10을 사용하도록이 줄을 업데이트합니다.

distributionUrl=https\://downloads.gradle.org/distributions/gradle-2.10-all.zip
#Alternative url if the above does not work:
#distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip

Android 스튜디오 환경 설정에서 '기본 Gradle 래퍼 사용'이 선택되어 있는지 확인합니다. Gradle 데몬이 다시 시작되도록 Android Studio를 다시 시작하는 것이 좋습니다.

"많은 경우 Gradle 2.9는 증분 빌드를 수행 할 때 Gradle 2.8보다 훨씬 빠릅니다."

출처 : docs.gradle.org/current/release-notes


나를 위해 일한 유일한 해결책은 즉시 실행을 비활성화하는 것입니다.

Android Studio-> Preferences-> Build, Execution, Deployment-> Instant Run-> 'Enable instant run [...]'선택 취소

빌드가 2 분에서 40 초로 변경되었습니다.


나는 같은 문제에 직면했고 마침내 그것을 해결하는 데 약 10 시간이 걸렸으므로 당신의 느낌을 알고 있습니다.

많이 봤고, 당신이했던 것과 똑같은 구성 작업을했고, 조금 도움이 되더라도 실제 앱을 컴파일하고 실행하는 것은 여전히 ​​엉덩이에 고통 스러웠습니다 (때로는 코드 한 줄을 변경했을 때 2-3 분이 걸렸습니다. 하지만 더 많은 작업을했을 때 보통 8 분이 걸렸고 그 시간 동안 컴퓨터가 완전히 멈췄습니다.)

그러나 충분한 대화가 있습니다. 'app : transformClassesWithDexForDebug'가하는 일은 Dalvik (pre-5.0, api 21) OS 버전에 대한 일부 종속성을 해결하고 중요한 것은 많은 시간이 걸린다는 것입니다. 21 이상에서 앱을 테스트 할 수 있으므로 개발에는 필요하지 않으므로 개발 및 출시를 위해 별도의 제품 버전을 만드세요. 다음은 그것을 사용하는 내 gradle 빌드입니다.

apply plugin: 'com.android.application'

final VERSION_MAJOR = 0
final VERSION_MINOR = 0
final VERSION_PATCH = 0
final VERSION_BUILD = 1

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.app"
        minSdkVersion 15
        targetSdkVersion 23
        multiDexEnabled true
        versionName "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}.${VERSION_BUILD}"
        versionCode VERSION_MAJOR * 10000000 + VERSION_MINOR * 100000 + VERSION_PATCH * 1000 + VERSION_BUILD
    }

    dexOptions {
        incremental = true;
        preDexLibraries = false
        javaMaxHeapSize "2g"
    }


    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    productFlavors {
        dev {
            minSdkVersion 21
            applicationId = "com.app.test"
        }
        prod {
            minSdkVersion 15
            applicationId = "com.app" // you don't need it, but can be useful

        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/ASL2.0'
    }
    lintOptions {
        checkReleaseBuilds false
        abortOnError true
    }

}

afterEvaluate {
    tasks.matching {
        it.name.startsWith('dex')
    }.each { dx ->
        if (dx.additionalParameters == null) {
            dx.additionalParameters = ['--multi-dex']
        } else {
            dx.additionalParameters += '--multi-dex'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
   ... 
}

Next thing is to make sure you are actually building your app with this build variant. Click on View -> Tool Windows -> Build tools and make sure you have build variant set to 'devDebug'

For some people this might be enough. I found a lot of threads here in SO and also on reddit that ended with this product flavor thing, but this didn't help me at all actually. What helped me is to uprade gradle manually. Since you already tried to do it, I think you are on the right track, but I would suggest using newer gradle version 2.9 which has '40% improved performance' over 2.8.


That seems like part of the new Instant Run mechanism introduced in Android Studio 2.0 preview, which is responsible to instrument every methods in your app to create execution branch for future code patch. I'm afraid that's why it is extremely slow.

It's weird this task is still taking place even if Instant Run is disabled. I have to downgrade "com.android.tools.build:gradle" to 1.3.0 to avoid that task.


Does your application have a database? Does the DB have a big size?

If yes:

  • remove the DB from assets folder (or wherever you keep it) and do a build
  • measure the difference in build times
  • IN MY CASE: it was a dramatic difference from 45 sec down to 15 sec

If No:

  • Monitor Gradle console during incremental builds and see what operation is taking the most time

참고URL : https://stackoverflow.com/questions/34158995/gradle-build-slow-on-transformclasseswithdexfordebug

반응형