IDEA的火焰图简单使用

1. 火焰图是什么?

简单来说就是用来查看程序耗时的一张图
如何读懂火焰图?

2. mac上如何生成火焰图

找了一圈,原来idea原本就支持…

3. 测试代码

package org.example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StepTimeMark {
    private List<Long> times = new ArrayList<>();

    private int type;
    public long getTime() {
        if (type == 1) {
            return System.nanoTime();
        }
        return System.currentTimeMillis();
    }
    public StepTimeMark(int type) {
        times.add(getTime());
    }
    public void mark() {
        times.add(getTime());
    }
    public void end(String msg, long time) {
        times.add(getTime());
        Long aLong = times.get(0);
        Long aLong1 = times.get(times.size() - 1);
        long stepAllTime = aLong1 - aLong;
        if (stepAllTime >= time) {
            List<Long> setTimes = new ArrayList<>();
            for(int i = 1; i < times.size(); ++i) {
                setTimes.add(times.get(i) - times.get(i - 1));
            }
            String str = setTimes.stream().map(String::valueOf).collect(Collectors.joining("\t"));
            System.out.printf("%s:%s cost time: %s%n", msg, str, stepAllTime);
            System.out.print(msg);
        }
    }

    public static void main(String[] args) throws Exception {
        StepTimeMark stepTimeMark = new StepTimeMark(0);
        Thread.sleep(1200);
        stepTimeMark.mark();
        Thread.sleep(30);
        stepTimeMark.mark();

        Thread.sleep(100);
        stepTimeMark.end("sss", 500 );
    }
 }

package org.example;

import groovy.lang.GroovyShell;

public class LGroovyShell {


    public static void main(String[] args) throws Exception {

        StepTimeMark stepTimeMark = new StepTimeMark(0);
        String script = "def add(a, b) {\n" +
                "    return a + b\n" +
                "}\n" +
                "add(a,b)";
        GroovyShell groovyShell = new GroovyShell();

        groovyShell.setVariable("a", 1);
        groovyShell.setVariable("b", 2);
        stepTimeMark.mark();
        ss();
        stepTimeMark.mark();
        Object evaluate = groovyShell.evaluate(script);
        System.out.println(evaluate);
        stepTimeMark.end("step time", 0);
    }

    public static void ss () throws Exception {
        for(int i = 0 ; i < 10000; ++i) {
            for(int j = 0 ; j < 10000; ++j) {
                System.out.println(i * j);
            }
        }
    }
}

IDEA的火焰图简单使用_第1张图片

4. 结果

step time:230	219726	381 cost time: 220337
step time
Process finished with exit code 0

可以看到 ss函数跑了接近219s
火焰图如下:

没想到还要点击火焰图上的➕

现在可以看到 ss函数的恐怖耗时了吧。也可以看到打印出来这个系统调用的耗时挺大。

你可能感兴趣的:(杂记,intellij-idea,java,ide)