You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Profiler.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client;
  17. import java.util.ArrayList;
  18. import java.util.Collection;
  19. import java.util.Collections;
  20. import java.util.Comparator;
  21. import java.util.HashMap;
  22. import java.util.HashSet;
  23. import java.util.LinkedHashMap;
  24. import java.util.LinkedList;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Set;
  28. import java.util.logging.Logger;
  29. import com.google.gwt.core.client.Duration;
  30. import com.google.gwt.core.client.GWT;
  31. import com.google.gwt.core.client.JavaScriptObject;
  32. import com.google.gwt.core.client.JsArray;
  33. /**
  34. * Lightweight profiling tool that can be used to collect profiling data with
  35. * zero overhead unless enabled. To enable profiling, add
  36. * <code>&lt;set-property name="vaadin.profiler" value="true" /&gt;</code> to
  37. * your .gwt.xml file.
  38. *
  39. * @author Vaadin Ltd
  40. * @since 7.0.0
  41. */
  42. public class Profiler {
  43. private static RelativeTimeSupplier RELATIVE_TIME_SUPPLIER;
  44. private static final String EVT_GROUP = "VaadinProfiler";
  45. private static ProfilerResultConsumer consumer;
  46. /**
  47. * Class to include using deferred binding to enable the profiling.
  48. *
  49. * @author Vaadin Ltd
  50. * @since 7.0.0
  51. */
  52. public static class EnabledProfiler extends Profiler {
  53. @Override
  54. protected boolean isImplEnabled() {
  55. return true;
  56. }
  57. }
  58. /**
  59. * Interface for getting data from the {@link Profiler}.
  60. * <p>
  61. * <b>Warning!</b> This interface is most likely to change in the future
  62. *
  63. * @since 7.1
  64. * @author Vaadin Ltd
  65. */
  66. public interface ProfilerResultConsumer {
  67. public void addProfilerData(Node rootNode, List<Node> totals);
  68. public void addBootstrapData(LinkedHashMap<String, Double> timings);
  69. }
  70. /**
  71. * A hierarchical representation of the time spent running a named block of
  72. * code.
  73. * <p>
  74. * <b>Warning!</b> This class is most likely to change in the future and is
  75. * therefore defined in this class in an internal package instead of
  76. * Profiler where it might seem more logical.
  77. */
  78. public static class Node {
  79. private final String name;
  80. private final LinkedHashMap<String, Node> children = new LinkedHashMap<>();
  81. private double time = 0;
  82. private int count = 0;
  83. private double enterTime = 0;
  84. private double minTime = 1000000000;
  85. private double maxTime = 0;
  86. /**
  87. * Create a new node with the given name.
  88. *
  89. * @param name
  90. */
  91. public Node(String name) {
  92. this.name = name;
  93. }
  94. /**
  95. * Gets the name of the node.
  96. *
  97. * @return the name of the node
  98. */
  99. public String getName() {
  100. return name;
  101. }
  102. /**
  103. * Creates a new child node or retrieves and existing child and updates
  104. * its total time and hit count.
  105. *
  106. * @param name
  107. * the name of the child
  108. * @param timestamp
  109. * the timestamp for when the node is entered
  110. * @return the child node object
  111. */
  112. public Node enterChild(String name, double timestamp) {
  113. Node child = children.get(name);
  114. if (child == null) {
  115. child = new Node(name);
  116. children.put(name, child);
  117. }
  118. child.enterTime = timestamp;
  119. child.count++;
  120. return child;
  121. }
  122. /**
  123. * Gets the total time spent in this node, including time spent in sub
  124. * nodes.
  125. *
  126. * @return the total time spent, in milliseconds
  127. */
  128. public double getTimeSpent() {
  129. return time;
  130. }
  131. /**
  132. * Gets the minimum time spent for one invocation of this node,
  133. * including time spent in sub nodes.
  134. *
  135. * @return the time spent for the fastest invocation, in milliseconds
  136. */
  137. public double getMinTimeSpent() {
  138. return minTime;
  139. }
  140. /**
  141. * Gets the maximum time spent for one invocation of this node,
  142. * including time spent in sub nodes.
  143. *
  144. * @return the time spent for the slowest invocation, in milliseconds
  145. */
  146. public double getMaxTimeSpent() {
  147. return maxTime;
  148. }
  149. /**
  150. * Gets the number of times this node has been entered.
  151. *
  152. * @return the number of times the node has been entered
  153. */
  154. public int getCount() {
  155. return count;
  156. }
  157. /**
  158. * Gets the total time spent in this node, excluding time spent in sub
  159. * nodes.
  160. *
  161. * @return the total time spent, in milliseconds
  162. */
  163. public double getOwnTime() {
  164. double time = getTimeSpent();
  165. for (Node node : children.values()) {
  166. time -= node.getTimeSpent();
  167. }
  168. return time;
  169. }
  170. /**
  171. * Gets the child nodes of this node.
  172. *
  173. * @return a collection of child nodes
  174. */
  175. public Collection<Node> getChildren() {
  176. return Collections.unmodifiableCollection(children.values());
  177. }
  178. @Override
  179. public String toString() {
  180. return getStringRepresentation("");
  181. }
  182. public String getStringRepresentation(String prefix) {
  183. if (getName() == null) {
  184. return "";
  185. }
  186. String msg = prefix + " " + getName() + " in "
  187. + roundToSignificantFigures(getTimeSpent()) + " ms.";
  188. if (getCount() > 1) {
  189. msg += " Invoked " + getCount() + " times ("
  190. + roundToSignificantFigures(getTimeSpent() / getCount())
  191. + " ms per time, min "
  192. + roundToSignificantFigures(getMinTimeSpent())
  193. + " ms, max "
  194. + roundToSignificantFigures(getMaxTimeSpent())
  195. + " ms).";
  196. }
  197. if (!children.isEmpty()) {
  198. double ownTime = getOwnTime();
  199. msg += " " + roundToSignificantFigures(ownTime)
  200. + " ms spent in own code";
  201. if (getCount() > 1) {
  202. msg += " ("
  203. + roundToSignificantFigures(ownTime / getCount())
  204. + " ms per time)";
  205. }
  206. msg += '.';
  207. }
  208. return msg;
  209. }
  210. private static double roundToSignificantFigures(double num) {
  211. // Number of significant digits
  212. int n = 3;
  213. if (num == 0) {
  214. return 0;
  215. }
  216. final double d = Math.ceil(Math.log10(num < 0 ? -num : num));
  217. final int power = n - (int) d;
  218. final double magnitude = Math.pow(10, power);
  219. final long shifted = Math.round(num * magnitude);
  220. return shifted / magnitude;
  221. }
  222. public void sumUpTotals(Map<String, Node> totals) {
  223. String name = getName();
  224. if (name != null) {
  225. Node totalNode = totals.get(name);
  226. if (totalNode == null) {
  227. totalNode = new Node(name);
  228. totals.put(name, totalNode);
  229. }
  230. totalNode.time += getOwnTime();
  231. totalNode.count += getCount();
  232. totalNode.minTime = roundToSignificantFigures(
  233. Math.min(totalNode.minTime, getMinTimeSpent()));
  234. totalNode.maxTime = roundToSignificantFigures(
  235. Math.max(totalNode.maxTime, getMaxTimeSpent()));
  236. }
  237. for (Node node : children.values()) {
  238. node.sumUpTotals(totals);
  239. }
  240. }
  241. /**
  242. * @param timestamp
  243. */
  244. public void leave(double timestamp) {
  245. double elapsed = (timestamp - enterTime);
  246. time += elapsed;
  247. enterTime = 0;
  248. if (elapsed < minTime) {
  249. minTime = elapsed;
  250. }
  251. if (elapsed > maxTime) {
  252. maxTime = elapsed;
  253. }
  254. }
  255. }
  256. private static final class GwtStatsEvent extends JavaScriptObject {
  257. protected GwtStatsEvent() {
  258. // JSO constructor
  259. }
  260. private native String getEvtGroup()
  261. /*-{
  262. return this.EVT_GROUP;
  263. }-*/;
  264. private native double getMillis()
  265. /*-{
  266. return this.millis;
  267. }-*/;
  268. private native String getSubSystem()
  269. /*-{
  270. return this.subSystem;
  271. }-*/;
  272. private native String getType()
  273. /*-{
  274. return this.type;
  275. }-*/;
  276. private native String getModuleName()
  277. /*-{
  278. return this.moduleName;
  279. }-*/;
  280. private native double getRelativeMillis()
  281. /*-{
  282. return this.relativeMillis;
  283. }-*/;
  284. private native boolean isExtendedEvent()
  285. /*-{
  286. return 'relativeMillis' in this;
  287. }-*/;
  288. public final String getEventName() {
  289. String group = getEvtGroup();
  290. if (EVT_GROUP.equals(group)) {
  291. return getSubSystem();
  292. } else {
  293. return group + "." + getSubSystem();
  294. }
  295. }
  296. }
  297. /**
  298. * Checks whether the profiling gathering is enabled.
  299. *
  300. * @return <code>true</code> if the profiling is enabled, else
  301. * <code>false</code>
  302. */
  303. public static boolean isEnabled() {
  304. // This will be fully inlined by the compiler
  305. Profiler create = GWT.create(Profiler.class);
  306. return create.isImplEnabled();
  307. }
  308. /**
  309. * Enters a named block. There should always be a matching invocation of
  310. * {@link #leave(String)} when leaving the block. Calls to this method will
  311. * be removed by the compiler unless profiling is enabled.
  312. *
  313. * @param name
  314. * the name of the entered block
  315. */
  316. public static void enter(String name) {
  317. if (isEnabled()) {
  318. logGwtEvent(name, "begin");
  319. }
  320. }
  321. /**
  322. * Leaves a named block. There should always be a matching invocation of
  323. * {@link #enter(String)} when entering the block. Calls to this method will
  324. * be removed by the compiler unless profiling is enabled.
  325. *
  326. * @param name
  327. * the name of the left block
  328. */
  329. public static void leave(String name) {
  330. if (isEnabled()) {
  331. logGwtEvent(name, "end");
  332. }
  333. }
  334. /**
  335. * Returns time relative to the particular page load time. The value should
  336. * not be used directly but rather difference between two values returned by
  337. * this method should be used to compare measurements.
  338. *
  339. * @since 7.6
  340. */
  341. public static double getRelativeTimeMillis() {
  342. return RELATIVE_TIME_SUPPLIER.getRelativeTime();
  343. }
  344. private static final native void logGwtEvent(String name, String type)
  345. /*-{
  346. $wnd.__gwtStatsEvent({
  347. evtGroup: @com.vaadin.client.Profiler::EVT_GROUP,
  348. moduleName: @com.google.gwt.core.client.GWT::getModuleName()(),
  349. millis: (new Date).getTime(),
  350. sessionId: undefined,
  351. subSystem: name,
  352. type: type,
  353. relativeMillis: @com.vaadin.client.Profiler::getRelativeTimeMillis()()
  354. });
  355. }-*/;
  356. /**
  357. * Resets the collected profiler data. Calls to this method will be removed
  358. * by the compiler unless profiling is enabled.
  359. */
  360. public static void reset() {
  361. if (isEnabled()) {
  362. /*
  363. * Old implementations might call reset for initialization, so
  364. * ensure it is initialized here as well. Initialization has no side
  365. * effects if already done.
  366. */
  367. initialize();
  368. clearEventsList();
  369. }
  370. }
  371. /**
  372. * Initializes the profiler. This should be done before calling any other
  373. * function in this class. Failing to do so might cause undesired behavior.
  374. * This method has no side effects if the initialization has already been
  375. * done.
  376. * <p>
  377. * Please note that this method should be called even if the profiler is not
  378. * enabled because it will then remove a logger function that might have
  379. * been included in the HTML page and that would leak memory unless removed.
  380. * </p>
  381. *
  382. * @since 7.0.2
  383. */
  384. public static void initialize() {
  385. if (hasHighPrecisionTime()) {
  386. RELATIVE_TIME_SUPPLIER = new HighResolutionTimeSupplier();
  387. } else {
  388. RELATIVE_TIME_SUPPLIER = new DefaultRelativeTimeSupplier();
  389. }
  390. if (isEnabled()) {
  391. ensureLogger();
  392. } else {
  393. ensureNoLogger();
  394. }
  395. }
  396. /**
  397. * Outputs the gathered profiling data to the debug console.
  398. */
  399. public static void logTimings() {
  400. if (!isEnabled()) {
  401. getLogger().warning(
  402. "Profiler is not enabled, no data has been collected.");
  403. return;
  404. }
  405. LinkedList<Node> stack = new LinkedList<>();
  406. Node rootNode = new Node(null);
  407. stack.add(rootNode);
  408. JsArray<GwtStatsEvent> gwtStatsEvents = getGwtStatsEvents();
  409. if (gwtStatsEvents.length() == 0) {
  410. getLogger().warning(
  411. "No profiling events recorded, this might happen if another __gwtStatsEvent handler is installed.");
  412. return;
  413. }
  414. Set<Node> extendedTimeNodes = new HashSet<>();
  415. for (int i = 0; i < gwtStatsEvents.length(); i++) {
  416. GwtStatsEvent gwtStatsEvent = gwtStatsEvents.get(i);
  417. if (!EVT_GROUP.equals(gwtStatsEvent.getEvtGroup())) {
  418. // Only log our own events to avoid problems with events which
  419. // are not of type start+end
  420. continue;
  421. }
  422. String eventName = gwtStatsEvent.getEventName();
  423. String type = gwtStatsEvent.getType();
  424. boolean isExtendedEvent = gwtStatsEvent.isExtendedEvent();
  425. boolean isBeginEvent = "begin".equals(type);
  426. Node stackTop = stack.getLast();
  427. boolean inEvent = eventName.equals(stackTop.getName())
  428. && !isBeginEvent;
  429. if (!inEvent && stack.size() >= 2
  430. && eventName.equals(stack.get(stack.size() - 2).getName())
  431. && !isBeginEvent) {
  432. // back out of sub event
  433. if (extendedTimeNodes.contains(stackTop) && isExtendedEvent) {
  434. stackTop.leave(gwtStatsEvent.getRelativeMillis());
  435. } else {
  436. stackTop.leave(gwtStatsEvent.getMillis());
  437. }
  438. stack.removeLast();
  439. stackTop = stack.getLast();
  440. inEvent = true;
  441. }
  442. if (type.equals("end")) {
  443. if (!inEvent) {
  444. getLogger().severe("Got end event for " + eventName
  445. + " but is currently in " + stackTop.getName());
  446. return;
  447. }
  448. Node previousStackTop = stack.removeLast();
  449. if (extendedTimeNodes.contains(previousStackTop)) {
  450. previousStackTop.leave(gwtStatsEvent.getRelativeMillis());
  451. } else {
  452. previousStackTop.leave(gwtStatsEvent.getMillis());
  453. }
  454. } else {
  455. double millis = isExtendedEvent
  456. ? gwtStatsEvent.getRelativeMillis()
  457. : gwtStatsEvent.getMillis();
  458. if (!inEvent) {
  459. stackTop = stackTop.enterChild(eventName, millis);
  460. stack.add(stackTop);
  461. if (isExtendedEvent) {
  462. extendedTimeNodes.add(stackTop);
  463. }
  464. }
  465. if (!isBeginEvent) {
  466. // Create sub event
  467. Node subNode = stackTop.enterChild(eventName + "." + type,
  468. millis);
  469. if (isExtendedEvent) {
  470. extendedTimeNodes.add(subNode);
  471. }
  472. stack.add(subNode);
  473. }
  474. }
  475. }
  476. if (stack.size() != 1) {
  477. getLogger().warning("Not all nodes are left, the last node is "
  478. + stack.getLast().getName());
  479. return;
  480. }
  481. Map<String, Node> totals = new HashMap<>();
  482. rootNode.sumUpTotals(totals);
  483. List<Node> totalList = new ArrayList<>(totals.values());
  484. Collections.sort(totalList, new Comparator<Node>() {
  485. @Override
  486. public int compare(Node o1, Node o2) {
  487. return (int) (o2.getTimeSpent() - o1.getTimeSpent());
  488. }
  489. });
  490. if (getConsumer() != null) {
  491. getConsumer().addProfilerData(stack.getFirst(), totalList);
  492. }
  493. }
  494. /**
  495. * Overridden in {@link EnabledProfiler} to make {@link #isEnabled()} return
  496. * true if GWT.create returns that class.
  497. *
  498. * @return <code>true</code> if the profiling is enabled, else
  499. * <code>false</code>
  500. */
  501. protected boolean isImplEnabled() {
  502. return false;
  503. }
  504. /**
  505. * Outputs the time passed since various events recored in
  506. * performance.timing if supported by the browser.
  507. */
  508. public static void logBootstrapTimings() {
  509. if (isEnabled()) {
  510. double now = Duration.currentTimeMillis();
  511. String[] keys = { "navigationStart", "unloadEventStart",
  512. "unloadEventEnd", "redirectStart", "redirectEnd",
  513. "fetchStart", "domainLookupStart", "domainLookupEnd",
  514. "connectStart", "connectEnd", "requestStart",
  515. "responseStart", "responseEnd", "domLoading",
  516. "domInteractive", "domContentLoadedEventStart",
  517. "domContentLoadedEventEnd", "domComplete", "loadEventStart",
  518. "loadEventEnd" };
  519. LinkedHashMap<String, Double> timings = new LinkedHashMap<>();
  520. for (String key : keys) {
  521. double value = getPerformanceTiming(key);
  522. if (value == 0) {
  523. // Ignore missing value
  524. continue;
  525. }
  526. timings.put(key, Double.valueOf(now - value));
  527. }
  528. if (timings.isEmpty()) {
  529. getLogger().info(
  530. "Bootstrap timings not supported, please ensure your browser supports performance.timing");
  531. return;
  532. }
  533. if (getConsumer() != null) {
  534. getConsumer().addBootstrapData(timings);
  535. }
  536. }
  537. }
  538. private static final native double getPerformanceTiming(String name)
  539. /*-{
  540. if ($wnd.performance && $wnd.performance.timing && $wnd.performance.timing[name]) {
  541. return $wnd.performance.timing[name];
  542. } else {
  543. return 0;
  544. }
  545. }-*/;
  546. private static native JsArray<GwtStatsEvent> getGwtStatsEvents()
  547. /*-{
  548. return $wnd.vaadin.gwtStatsEvents || [];
  549. }-*/;
  550. /**
  551. * Add logger if it's not already there, also initializing the event array
  552. * if needed.
  553. */
  554. private static native void ensureLogger()
  555. /*-{
  556. if (typeof $wnd.__gwtStatsEvent != 'function') {
  557. if (typeof $wnd.vaadin.gwtStatsEvents != 'object') {
  558. $wnd.vaadin.gwtStatsEvents = [];
  559. }
  560. $wnd.__gwtStatsEvent = function(event) {
  561. $wnd.vaadin.gwtStatsEvents.push(event);
  562. return true;
  563. }
  564. }
  565. }-*/;
  566. /**
  567. * Remove logger function and event array if it seems like the function has
  568. * been added by us.
  569. */
  570. private static native void ensureNoLogger()
  571. /*-{
  572. if (typeof $wnd.vaadin.gwtStatsEvents == 'object') {
  573. delete $wnd.vaadin.gwtStatsEvents;
  574. if (typeof $wnd.__gwtStatsEvent == 'function') {
  575. $wnd.__gwtStatsEvent = function() { return true; };
  576. }
  577. }
  578. }-*/;
  579. private static native JsArray<GwtStatsEvent> clearEventsList()
  580. /*-{
  581. $wnd.vaadin.gwtStatsEvents = [];
  582. }-*/;
  583. /**
  584. * Sets the profiler result consumer that is used to output the profiler
  585. * data to the user.
  586. * <p>
  587. * <b>Warning!</b> This is internal API and should not be used by
  588. * applications or add-ons.
  589. *
  590. * @since 7.1.4
  591. * @param profilerResultConsumer
  592. * the consumer that gets profiler data
  593. */
  594. public static void setProfilerResultConsumer(
  595. ProfilerResultConsumer profilerResultConsumer) {
  596. if (consumer != null) {
  597. throw new IllegalStateException(
  598. "The consumer has already been set");
  599. }
  600. consumer = profilerResultConsumer;
  601. }
  602. private static ProfilerResultConsumer getConsumer() {
  603. return consumer;
  604. }
  605. private static Logger getLogger() {
  606. return Logger.getLogger(Profiler.class.getName());
  607. }
  608. private static native boolean hasHighPrecisionTime()
  609. /*-{
  610. return $wnd.performance && (typeof $wnd.performance.now == 'function');
  611. }-*/;
  612. private interface RelativeTimeSupplier {
  613. double getRelativeTime();
  614. }
  615. private static class DefaultRelativeTimeSupplier
  616. implements RelativeTimeSupplier {
  617. @Override
  618. public native double getRelativeTime()
  619. /*-{
  620. return (new Date).getTime();
  621. }-*/;
  622. }
  623. private static class HighResolutionTimeSupplier
  624. implements RelativeTimeSupplier {
  625. @Override
  626. public native double getRelativeTime()
  627. /*-{
  628. return $wnd.performance.now();
  629. }-*/;
  630. }
  631. }