首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 命令行編譯測量編譯時間:System.currentTimeMillis() 封裝工具類

     編輯:程式設計疑難解答

核心方法

在編譯腳本/工具類中記錄編譯前後時間戳:

public class CompileTimer {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        
        // 執行編譯邏輯:可調用 JavaCompiler API 或 Runtime.exec("javac ...")
        // 此處示例:模擬編譯耗時
        try { Thread.sleep(1234); } catch (InterruptedException ignored) {}
        
        long end = System.currentTimeMillis();
        System.out.println("編譯耗時: " + (end - start) + " ms");
    }
}

實際項目中測量編譯時間

  • Maven:maven-compiler-plugin 無內建計時,可用 maven-profile-plugin 或 CI 系統 (Jenkins/GitLab CI) 統計階段耗時。
  • Gradle:--profile 參數生成 HTML 報告含任務耗時。
  • IDE:IntelliJ IDEA Build 窗口顯示編譯耗時。
  • 自製工具:使用 javax.tools.JavaCompiler API 程式化編譯並計時。

JavaCompiler API 計時範例

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
Iterable files = fm.getJavaFileObjectsFromFiles(Arrays.asList(new File("Main.java")));

long start = System.nanoTime();
JavaCompiler.CompilationTask task = compiler.getTask(null, fm, null, null, null, files);
boolean success = task.call();
long end = System.nanoTime();

System.out.printf("編譯 %s, 耗時 %.2f ms%n", success ? "成功" : "失敗", (end - start) / 1e6);

注意

System.currentTimeMillis() 精度 ~10-15ms,**微基準測試請用 System.nanoTime()** (納秒級單調時鐘)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved