aboutsummaryrefslogtreecommitdiff
path: root/src/jdk/nashorn/internal/runtime/Timing.java
blob: e1d464d9267e24ad1239373128f64e03451943b5 (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/*
 * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
package jdk.nashorn.internal.runtime;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import jdk.nashorn.internal.codegen.CompileUnit;
import jdk.nashorn.internal.runtime.logging.DebugLogger;
import jdk.nashorn.internal.runtime.logging.Loggable;
import jdk.nashorn.internal.runtime.logging.Logger;

/**
 * Simple wallclock timing framework
 */
@Logger(name="time")
public final class Timing implements Loggable {

    private DebugLogger log;
    private TimeSupplier timeSupplier;
    private final boolean isEnabled;
    private final long startTime;

    private static final String LOGGER_NAME = Timing.class.getAnnotation(Logger.class).name();

    /**
     * Instantiate singleton timer for ScriptEnvironment
     * @param isEnabled true if enabled, otherwise we keep the instance around
     *      for code brevity and "isEnabled" checks, but never instantiate anything
     *      inside it
     */
    public Timing(final boolean isEnabled) {
        this.isEnabled = isEnabled;
        this.startTime = System.nanoTime();
    }

    /**
     * Get the log info accumulated by this Timing instance
     * @return log info as one string
     */
    public String getLogInfo() {
        assert isEnabled();
        return timeSupplier.get();
    }

    /**
     * Get the log info accumulated by this Timing instance
     * @return log info as and array of strings, one per line
     */
    public String[] getLogInfoLines() {
        assert isEnabled();
        return timeSupplier.getStrings();
    }

    /**
     * Check if timing is enabled
     * @return true if timing is enabled
     */
    boolean isEnabled() {
        return isEnabled;
    }

    /**
     * When timing, this can be called to register a new module for timing
     * or add to its accumulated time
     *
     * @param module   module name
     * @param durationNano duration to add to accumulated time for module, in nanoseconds.
     */
    public void accumulateTime(final String module, final long durationNano) {
        if (isEnabled()) {
            ensureInitialized(Context.getContextTrusted());
            timeSupplier.accumulateTime(module, durationNano);
        }
    }

    private DebugLogger ensureInitialized(final Context context) {
        //lazy init, as there is not necessarily a context available when
        //a ScriptEnvironment gets initialize
        if (isEnabled() && log == null) {
            log = initLogger(context);
            if (log.isEnabled()) {
                this.timeSupplier = new TimeSupplier();
                Runtime.getRuntime().addShutdownHook(
                        new Thread() {
                            @Override
                            public void run() {
                                //System.err.println because the context and the output streams may be gone
                                //when the shutdown hook executes
                                final StringBuilder sb = new StringBuilder();
                                for (final String str : timeSupplier.getStrings()) {
                                    sb.append('[').
                                        append(Timing.getLoggerName()).
                                        append("] ").
                                        append(str).
                                        append('\n');
                                }
                                System.err.print(sb);
                            }
                        });
            }
        }
        return log;
    }

    static String getLoggerName() {
        return LOGGER_NAME;
    }

    @Override
    public DebugLogger initLogger(final Context context) {
        return context.getLogger(this.getClass());
    }

    @Override
    public DebugLogger getLogger() {
        return log;
    }

    /**
     * Takes a duration in nanoseconds, and returns a string representation of it rounded to milliseconds.
     * @param durationNano duration in nanoseconds
     * @return the string representing the duration in milliseconds.
     */
    public static String toMillisPrint(final long durationNano) {
        return Long.toString(TimeUnit.NANOSECONDS.toMillis(durationNano));
    }

    final class TimeSupplier implements Supplier<String> {
        private final Map<String, Long> timings;

        TimeSupplier() {
            timings   = new LinkedHashMap<>();
        }

        String[] getStrings() {
            final List<String> strs = new ArrayList<>();
            final BufferedReader br = new BufferedReader(new StringReader(get()));
            String line;
            try {
                while ((line = br.readLine()) != null) {
                    strs.add(line);
                }
            } catch (final IOException e) {
                throw new RuntimeException(e);
            }
            return strs.toArray(new String[strs.size()]);
        }

        @Override
        public String get() {
            final long t = System.nanoTime();

            long knownTime = 0L;
            int  maxKeyLength = 0;
            int  maxValueLength = 0;

            for (final Map.Entry<String, Long> entry : timings.entrySet()) {
                maxKeyLength   = Math.max(maxKeyLength, entry.getKey().length());
                maxValueLength = Math.max(maxValueLength, toMillisPrint(entry.getValue()).length());
            }
            maxKeyLength++;

            final StringBuilder sb = new StringBuilder();
            sb.append("Accumulated compilation phase timings:\n\n");
            for (final Map.Entry<String, Long> entry : timings.entrySet()) {
                int len;

                len = sb.length();
                sb.append(entry.getKey());
                len = sb.length() - len;

                while (len++ < maxKeyLength) {
                    sb.append(' ');
                }

                final Long duration = entry.getValue();
                final String strDuration = toMillisPrint(duration);
                len = strDuration.length();
                for (int i = 0; i < maxValueLength - len; i++) {
                    sb.append(' ');
                }

                sb.append(strDuration).
                    append(" ms\n");

                knownTime += duration;
            }

            final long total = t - startTime;
            sb.append('\n');
            sb.append("Total runtime: ").
                append(toMillisPrint(total)).
                append(" ms (Non-runtime: ").
                append(toMillisPrint(knownTime)).
                append(" ms [").
                append((int)(knownTime * 100.0 / total)).
                append("%])");

            sb.append("\n\nEmitted compile units: ").
                append(CompileUnit.getEmittedUnitCount());

            return sb.toString();
        }

        private void accumulateTime(final String module, final long duration) {
            Long accumulatedTime = timings.get(module);
            if (accumulatedTime == null) {
                accumulatedTime = 0L;
            }
            timings.put(module, accumulatedTime + duration);
        }
    }
}