11

对于一些专业的 Java 程序员来说,这可能是一个愚蠢的问题,但我现在要疯了,所以我还在问。请指导我正确的方向有人。

如何分析哪个方法/partOfMethod 在我的 java 程序中消耗更多时间?

(我正在使用 Eclipse 和 Junit)

4

6 回答 6

15

使用 jvisualvm。它现在与 JDK 捆绑在一起,但也有一个独立版本,它是最新的。通常,当您启动它时,您可以选择要连接到哪个正在运行的 java 进程(这很可能是我们正在运行的单元测试)。您可以指定需要跟踪的合格类名过滤器。通常,会出现一些类检测,您将能够跟踪分配给每个方法的处理时间(以及累积时间)。

于 2013-01-28T09:19:02.660 回答
3

您需要获取Java 分析器其中一些在 Eclipse 中集成得很好

除此之外,您还可以使用自定义分析器类(如果您没有太多的分析工作要做并且您已经怀疑存在一些瓶颈)。

这是一个简单的类来做到这一点:

/**
 * Small helper class to profile the code, take timing, ...
 * 
 * To use this, simply call the start method with an identifier. When you want to measure the time, call the stop method
 * with the same identifier. To output statistics, simply call the toString method or the toCsv method to create a CSV
 * file with the profiler information.
 * 
 * @author Vincent Prat @ MarvinLabs
 */
public class Profiler {

    private static final int THEORETICAL_MAX_NAME_LENGTH = 50;

    private static Profiler singletonInstance = null;

    private Map<String, Profile> profiles; // Fast access to profiles by name
    private List<Profile> profilesStack; // Profiles as created chronologically

    /**
     * Get access to the singleton instance (create it if necessary)
     */
    public static Profiler getInstance() {
        if (singletonInstance == null) {
            singletonInstance = new Profiler();
        }
        return singletonInstance;
    }

    /**
     * Protected constructor for singleton
     */
    protected Profiler() {
        profiles = new HashMap<String, Profiler.Profile>();
        profilesStack = new ArrayList<Profile>();
    }

    /**
     * Start a profile. If the profile does not exist, it will be created. If it exists, a new round of measure is
     * taken.
     * 
     * @param name
     *            The name of the profile. If possible, less than Profiler.THEORETICAL_MAX_NAME_LENGTH characters
     * 
     * @see Profiler.THEORETICAL_MAX_NAME_LENGTH
     */
    public void start(String name) {
        Profile p = profiles.get(name);
        if (p == null) {
            p = new Profile(name);
            profiles.put(name, p);
            profilesStack.add(p);
        }
        p.start();
    }

    /**
     * Stop a profile and compute some statistics about it.
     * 
     * @param name
     *            The name of the profile as declared in the corresponding start method
     */
    public void stop(String name) {
        Profile p = profiles.get(name);
        if (p == null) {
            throw new RuntimeException("The profile " + name + " has not been created by a call to the start() method!");
        }
        p.stop();
    }

    /**
     * Clear all the current measures. Not to be called within any start/stop pair.
     */
    public void reset() {
        profiles.clear();
    }

    /**
     * Build a string containing all the information about the measures we have taken so far.
     */
    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer();
        for (Profile p : profilesStack) {
            sb.append(p.toString());
            sb.append("\n");
        }
        return sb.toString();
    }

    /**
     * Output the measures to an output string
     */
    public void toCsvFile(OutputStream os) throws IOException {
        Profile.writeCsvHeader(os);
        for (Profile p : profilesStack) {
            p.writeCsvLine(os);
        }
    }

    /**
     * Profile information. It stores statistics per named profile.
     * 
     * @author Vincent Prat @ MarvinLabs
     */
    private static class Profile {
        private static final String CSV_HEADERS = "Name, Call Count, Total Time (ms), Average Time (ms), Min Time (ms), Max Time (ms), Delta Time (ms), Delta Ratio (%)\n";

        private static final String FORMAT_STRING = "%-" + THEORETICAL_MAX_NAME_LENGTH + "."
                + THEORETICAL_MAX_NAME_LENGTH
                + "s: %3d calls, total %5d ms, avg %5d ms, min %5d ms, max %5d ms, delta %5d ms (%d%%)";

        private static final String CSV_FORMAT_STRING = "%s,%d,%d,%d,%d,%d,%d,%d\n";

        private String name;
        private long startTime;
        private long callCount;
        private long totalTime;
        private long minTime;
        private long maxTime;

        public Profile(String name) {
            this.name = name;
            this.callCount = 0;
            this.totalTime = 0;
            this.startTime = 0;
            this.minTime = Long.MAX_VALUE;
            this.maxTime = Long.MIN_VALUE;
        }

        public void start() {
            startTime = System.currentTimeMillis();
        }

        public void stop() {
            final long elapsed = (System.currentTimeMillis() - startTime);
            if (elapsed < minTime) minTime = elapsed;
            if (elapsed > maxTime) maxTime = elapsed;
            totalTime += elapsed;
            callCount++;
        }

        private String getFormattedStats(String format) {
            final long avgTime = callCount == 0 ? 0 : (long) totalTime / callCount;
            final long delta = maxTime - minTime;
            final double deltaRatio = avgTime == 0 ? 0 : 100.0 * ((double) 0.5 * delta / (double) avgTime);

            return String
                    .format(format, name, callCount, totalTime, avgTime, minTime, maxTime, delta, (int) deltaRatio);
        }

        @Override
        public String toString() {
            return getFormattedStats(FORMAT_STRING);
        }

        public static void writeCsvHeader(OutputStream os) throws IOException {
            os.write(CSV_HEADERS.getBytes());
        }

        public void writeCsvLine(OutputStream os) throws IOException {
            os.write(getFormattedStats(CSV_FORMAT_STRING).getBytes());
        }
    }
}

和示例用法:

Profiler.getInstance().start("marker1");
// Do something...

Profiler.getInstance().start("marker2");

// Something else...

Profiler.getInstance().stop("marker2");

// And some more...

Profiler.getInstance().stop("marker1");

// Output the profiling result
System.out.println(Profiler.getInstance().toString());
于 2013-01-28T09:17:19.210 回答
0

你可以看看Yourkit(商业软件),它可以监控内存、CPU等等。它有特殊的视图来显示方法中花费了多少时间(例如,您可以看到 40% 的执行时间花费在方法中xyz())。

于 2013-01-28T09:27:34.870 回答
0

称我为老式,但这是我认为最简单的方法:

long a, b, c, d;
a = System.currentTimeMillis();
// some code 1
b = System.currentTimeMillis();
// some code 2
c = System.currentTimeMillis();
// some code 3
d = System.currentTimeMillis();

System.out.println("Some code 1 took "+(b-a)+"mil to execute. ("+((b-a)/1000)+" seconds)");
System.out.println("Some code 2 took "+(c-b)+"mil to execute. ("+((c-b)/1000)+" seconds)");
System.out.println("Some code 3 took "+(d-c)+"mil to execute. ("+((d-c)/1000)+" seconds)");

希望这可以帮助 :)

于 2013-01-28T10:01:43.247 回答
-2

测量程序的哪一部分需要多少运行时间的过程称为“分析”。

eclipse 有很多分析插件。一个在这里描述

于 2013-01-28T09:18:30.570 回答
-2

有一些像IdeOne这样的在线工具可以让你花时间执行代码块。试试看!

于 2013-02-18T08:59:02.920 回答