summaryrefslogtreecommitdiff
path: root/src/main/java/org/javacs/Profiler.java
blob: c7b6911a6709767b589cc19218f4d15aad7d15c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package org.javacs;

import com.sun.source.util.*;
import java.net.URI;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.logging.Logger;

class Profiler implements TaskListener {
    Set<URI> files = new HashSet<>();
    Map<URI, Map<TaskEvent.Kind, Instant>> started = new HashMap<>();
    Map<TaskEvent.Kind, Duration> profile = new EnumMap<>(TaskEvent.Kind.class);

    @Override
    public void started(TaskEvent e) {
        var uri = e.getSourceFile().toUri();
        var kind = e.getKind();
        var fileStarted = started.computeIfAbsent(uri, __ -> new EnumMap<>(TaskEvent.Kind.class));
        fileStarted.put(kind, Instant.now());
        files.add(uri);
        // TODO show the user a warning when we're compiling a lot of files that aren't in the classpath
    }

    @Override
    public void finished(TaskEvent e) {
        var uri = e.getSourceFile().toUri();
        var kind = e.getKind();
        var fileStarted = started.computeIfAbsent(uri, __ -> new HashMap<>());
        var start = fileStarted.getOrDefault(kind, Instant.now());
        var elapsed = Duration.between(start, Instant.now());
        var soFar = profile.getOrDefault(kind, Duration.ZERO);
        var total = soFar.plus(elapsed);
        profile.put(kind, total);
    }

    void print() {
        var lines = new StringJoiner("; ");
        for (var kind : TaskEvent.Kind.values()) {
            if (!profile.containsKey(kind)) continue;
            var elapsed = profile.get(kind);
            var s = elapsed.getSeconds() + elapsed.getNano() / 1000.0 / 1000.0 / 1000.0;
            lines.add(String.format("%s: %.3fs", kind, s));
        }
        // TODO log names if n is small
        LOG.info(String.format("Compiled %d files: %s", files.size(), lines));
    }

    private static final Logger LOG = Logger.getLogger("main");
}