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 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. /*
  2. * Copyright 2000-2014 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 evtGroup = "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<String, Node>();
  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. private void buildRecursiveString(StringBuilder builder, String prefix) {
  179. if (getName() != null) {
  180. String msg = getStringRepresentation(prefix);
  181. builder.append(msg + '\n');
  182. }
  183. String childPrefix = prefix + "*";
  184. for (Node node : children.values()) {
  185. node.buildRecursiveString(builder, childPrefix);
  186. }
  187. }
  188. @Override
  189. public String toString() {
  190. return getStringRepresentation("");
  191. }
  192. public String getStringRepresentation(String prefix) {
  193. if (getName() == null) {
  194. return "";
  195. }
  196. String msg = prefix + " " + getName() + " in "
  197. + roundToSignificantFigures(getTimeSpent()) + " ms.";
  198. if (getCount() > 1) {
  199. msg += " Invoked "
  200. + getCount()
  201. + " times ("
  202. + roundToSignificantFigures(getTimeSpent() / getCount())
  203. + " ms per time, min "
  204. + roundToSignificantFigures(getMinTimeSpent())
  205. + " ms, max "
  206. + roundToSignificantFigures(getMaxTimeSpent())
  207. + " ms).";
  208. }
  209. if (!children.isEmpty()) {
  210. double ownTime = getOwnTime();
  211. msg += " " + roundToSignificantFigures(ownTime)
  212. + " ms spent in own code";
  213. if (getCount() > 1) {
  214. msg += " ("
  215. + roundToSignificantFigures(ownTime / getCount())
  216. + " ms per time)";
  217. }
  218. msg += '.';
  219. }
  220. return msg;
  221. }
  222. private static double roundToSignificantFigures(double num) {
  223. // Number of significant digits
  224. int n = 3;
  225. if (num == 0) {
  226. return 0;
  227. }
  228. final double d = Math.ceil(Math.log10(num < 0 ? -num : num));
  229. final int power = n - (int) d;
  230. final double magnitude = Math.pow(10, power);
  231. final long shifted = Math.round(num * magnitude);
  232. return shifted / magnitude;
  233. }
  234. public void sumUpTotals(Map<String, Node> totals) {
  235. String name = getName();
  236. if (name != null) {
  237. Node totalNode = totals.get(name);
  238. if (totalNode == null) {
  239. totalNode = new Node(name);
  240. totals.put(name, totalNode);
  241. }
  242. totalNode.time += getOwnTime();
  243. totalNode.count += getCount();
  244. totalNode.minTime = roundToSignificantFigures(Math.min(
  245. totalNode.minTime, getMinTimeSpent()));
  246. totalNode.maxTime = roundToSignificantFigures(Math.max(
  247. totalNode.maxTime, getMaxTimeSpent()));
  248. }
  249. for (Node node : children.values()) {
  250. node.sumUpTotals(totals);
  251. }
  252. }
  253. /**
  254. * @param timestamp
  255. */
  256. public void leave(double timestamp) {
  257. double elapsed = (timestamp - enterTime);
  258. time += elapsed;
  259. enterTime = 0;
  260. if (elapsed < minTime) {
  261. minTime = elapsed;
  262. }
  263. if (elapsed > maxTime) {
  264. maxTime = elapsed;
  265. }
  266. }
  267. }
  268. private static final class GwtStatsEvent extends JavaScriptObject {
  269. protected GwtStatsEvent() {
  270. // JSO constructor
  271. }
  272. private native String getEvtGroup()
  273. /*-{
  274. return this.evtGroup;
  275. }-*/;
  276. private native double getMillis()
  277. /*-{
  278. return this.millis;
  279. }-*/;
  280. private native String getSubSystem()
  281. /*-{
  282. return this.subSystem;
  283. }-*/;
  284. private native String getType()
  285. /*-{
  286. return this.type;
  287. }-*/;
  288. private native String getModuleName()
  289. /*-{
  290. return this.moduleName;
  291. }-*/;
  292. private native double getRelativeMillis()
  293. /*-{
  294. return this.relativeMillis;
  295. }-*/;
  296. private native boolean isExtendedEvent()
  297. /*-{
  298. return 'relativeMillis' in this;
  299. }-*/;
  300. public final String getEventName() {
  301. String group = getEvtGroup();
  302. if (evtGroup.equals(group)) {
  303. return getSubSystem();
  304. } else {
  305. return group + "." + getSubSystem();
  306. }
  307. }
  308. }
  309. /**
  310. * Checks whether the profiling gathering is enabled.
  311. *
  312. * @return <code>true</code> if the profiling is enabled, else
  313. * <code>false</code>
  314. */
  315. public static boolean isEnabled() {
  316. // This will be fully inlined by the compiler
  317. Profiler create = GWT.create(Profiler.class);
  318. return create.isImplEnabled();
  319. }
  320. /**
  321. * Enters a named block. There should always be a matching invocation of
  322. * {@link #leave(String)} when leaving the block. Calls to this method will
  323. * be removed by the compiler unless profiling is enabled.
  324. *
  325. * @param name
  326. * the name of the entered block
  327. */
  328. public static void enter(String name) {
  329. if (isEnabled()) {
  330. logGwtEvent(name, "begin");
  331. }
  332. }
  333. /**
  334. * Leaves a named block. There should always be a matching invocation of
  335. * {@link #enter(String)} when entering the block. Calls to this method will
  336. * be removed by the compiler unless profiling is enabled.
  337. *
  338. * @param name
  339. * the name of the left block
  340. */
  341. public static void leave(String name) {
  342. if (isEnabled()) {
  343. logGwtEvent(name, "end");
  344. }
  345. }
  346. /**
  347. * Returns time relative to the particular page load time. The value should
  348. * not be used directly but rather difference between two values returned by
  349. * this method should be used to compare measurements.
  350. *
  351. * @since 7.6
  352. */
  353. public static double getRelativeTimeMillis() {
  354. return RELATIVE_TIME_SUPPLIER.getRelativeTime();
  355. }
  356. private static native final void logGwtEvent(String name, String type)
  357. /*-{
  358. $wnd.__gwtStatsEvent({
  359. evtGroup: @com.vaadin.client.Profiler::evtGroup,
  360. moduleName: @com.google.gwt.core.client.GWT::getModuleName()(),
  361. millis: (new Date).getTime(),
  362. sessionId: undefined,
  363. subSystem: name,
  364. type: type,
  365. relativeMillis: @com.vaadin.client.Profiler::getRelativeTimeMillis()()
  366. });
  367. }-*/;
  368. /**
  369. * Resets the collected profiler data. Calls to this method will be removed
  370. * by the compiler unless profiling is enabled.
  371. */
  372. public static void reset() {
  373. if (isEnabled()) {
  374. /*
  375. * Old implementations might call reset for initialization, so
  376. * ensure it is initialized here as well. Initialization has no side
  377. * effects if already done.
  378. */
  379. initialize();
  380. clearEventsList();
  381. }
  382. }
  383. /**
  384. * Initializes the profiler. This should be done before calling any other
  385. * function in this class. Failing to do so might cause undesired behavior.
  386. * This method has no side effects if the initialization has already been
  387. * done.
  388. * <p>
  389. * Please note that this method should be called even if the profiler is not
  390. * enabled because it will then remove a logger function that might have
  391. * been included in the HTML page and that would leak memory unless removed.
  392. * </p>
  393. *
  394. * @since 7.0.2
  395. */
  396. public static void initialize() {
  397. if (hasHighPrecisionTime()) {
  398. RELATIVE_TIME_SUPPLIER = new HighResolutionTimeSupplier();
  399. } else {
  400. RELATIVE_TIME_SUPPLIER = new DefaultRelativeTimeSupplier();
  401. }
  402. if (isEnabled()) {
  403. ensureLogger();
  404. } else {
  405. ensureNoLogger();
  406. }
  407. }
  408. /**
  409. * Outputs the gathered profiling data to the debug console.
  410. */
  411. public static void logTimings() {
  412. if (!isEnabled()) {
  413. getLogger().warning(
  414. "Profiler is not enabled, no data has been collected.");
  415. return;
  416. }
  417. LinkedList<Node> stack = new LinkedList<Node>();
  418. Node rootNode = new Node(null);
  419. stack.add(rootNode);
  420. JsArray<GwtStatsEvent> gwtStatsEvents = getGwtStatsEvents();
  421. if (gwtStatsEvents.length() == 0) {
  422. getLogger()
  423. .warning(
  424. "No profiling events recorded, this might happen if another __gwtStatsEvent handler is installed.");
  425. return;
  426. }
  427. Set<Node> extendedTimeNodes = new HashSet<Node>();
  428. for (int i = 0; i < gwtStatsEvents.length(); i++) {
  429. GwtStatsEvent gwtStatsEvent = gwtStatsEvents.get(i);
  430. String eventName = gwtStatsEvent.getEventName();
  431. String type = gwtStatsEvent.getType();
  432. boolean isExtendedEvent = gwtStatsEvent.isExtendedEvent();
  433. boolean isBeginEvent = "begin".equals(type);
  434. Node stackTop = stack.getLast();
  435. boolean inEvent = eventName.equals(stackTop.getName())
  436. && !isBeginEvent;
  437. if (!inEvent && stack.size() >= 2
  438. && eventName.equals(stack.get(stack.size() - 2).getName())
  439. && !isBeginEvent) {
  440. // back out of sub event
  441. if (extendedTimeNodes.contains(stackTop) && isExtendedEvent) {
  442. stackTop.leave(gwtStatsEvent.getRelativeMillis());
  443. } else {
  444. stackTop.leave(gwtStatsEvent.getMillis());
  445. }
  446. stack.removeLast();
  447. stackTop = stack.getLast();
  448. inEvent = true;
  449. }
  450. if (type.equals("end")) {
  451. if (!inEvent) {
  452. getLogger().severe(
  453. "Got end event for " + eventName
  454. + " but is currently in "
  455. + stackTop.getName());
  456. return;
  457. }
  458. Node previousStackTop = stack.removeLast();
  459. if (extendedTimeNodes.contains(previousStackTop)) {
  460. previousStackTop.leave(gwtStatsEvent.getRelativeMillis());
  461. } else {
  462. previousStackTop.leave(gwtStatsEvent.getMillis());
  463. }
  464. } else {
  465. double millis = isExtendedEvent ? gwtStatsEvent
  466. .getRelativeMillis() : gwtStatsEvent.getMillis();
  467. if (!inEvent) {
  468. stackTop = stackTop.enterChild(eventName, millis);
  469. stack.add(stackTop);
  470. if (isExtendedEvent) {
  471. extendedTimeNodes.add(stackTop);
  472. }
  473. }
  474. if (!isBeginEvent) {
  475. // Create sub event
  476. Node subNode = stackTop.enterChild(eventName + "." + type,
  477. millis);
  478. if (isExtendedEvent) {
  479. extendedTimeNodes.add(subNode);
  480. }
  481. stack.add(subNode);
  482. }
  483. }
  484. }
  485. if (stack.size() != 1) {
  486. getLogger().warning(
  487. "Not all nodes are left, the last node is "
  488. + stack.getLast().getName());
  489. return;
  490. }
  491. Map<String, Node> totals = new HashMap<String, Node>();
  492. rootNode.sumUpTotals(totals);
  493. ArrayList<Node> totalList = new ArrayList<Node>(totals.values());
  494. Collections.sort(totalList, new Comparator<Node>() {
  495. @Override
  496. public int compare(Node o1, Node o2) {
  497. return (int) (o2.getTimeSpent() - o1.getTimeSpent());
  498. }
  499. });
  500. if (getConsumer() != null) {
  501. getConsumer().addProfilerData(stack.getFirst(), totalList);
  502. }
  503. }
  504. /**
  505. * Overridden in {@link EnabledProfiler} to make {@link #isEnabled()} return
  506. * true if GWT.create returns that class.
  507. *
  508. * @return <code>true</code> if the profiling is enabled, else
  509. * <code>false</code>
  510. */
  511. protected boolean isImplEnabled() {
  512. return false;
  513. }
  514. /**
  515. * Outputs the time passed since various events recored in
  516. * performance.timing if supported by the browser.
  517. */
  518. public static void logBootstrapTimings() {
  519. if (isEnabled()) {
  520. double now = Duration.currentTimeMillis();
  521. String[] keys = new String[] { "navigationStart",
  522. "unloadEventStart", "unloadEventEnd", "redirectStart",
  523. "redirectEnd", "fetchStart", "domainLookupStart",
  524. "domainLookupEnd", "connectStart", "connectEnd",
  525. "requestStart", "responseStart", "responseEnd",
  526. "domLoading", "domInteractive",
  527. "domContentLoadedEventStart", "domContentLoadedEventEnd",
  528. "domComplete", "loadEventStart", "loadEventEnd" };
  529. LinkedHashMap<String, Double> timings = new LinkedHashMap<String, Double>();
  530. for (String key : keys) {
  531. double value = getPerformanceTiming(key);
  532. if (value == 0) {
  533. // Ignore missing value
  534. continue;
  535. }
  536. timings.put(key, Double.valueOf(now - value));
  537. }
  538. if (timings.isEmpty()) {
  539. getLogger()
  540. .info("Bootstrap timings not supported, please ensure your browser supports performance.timing");
  541. return;
  542. }
  543. if (getConsumer() != null) {
  544. getConsumer().addBootstrapData(timings);
  545. }
  546. }
  547. }
  548. private static final native double getPerformanceTiming(String name)
  549. /*-{
  550. if ($wnd.performance && $wnd.performance.timing && $wnd.performance.timing[name]) {
  551. return $wnd.performance.timing[name];
  552. } else {
  553. return 0;
  554. }
  555. }-*/;
  556. private static native JsArray<GwtStatsEvent> getGwtStatsEvents()
  557. /*-{
  558. return $wnd.vaadin.gwtStatsEvents || [];
  559. }-*/;
  560. /**
  561. * Add logger if it's not already there, also initializing the event array
  562. * if needed.
  563. */
  564. private static native void ensureLogger()
  565. /*-{
  566. if (typeof $wnd.__gwtStatsEvent != 'function') {
  567. if (typeof $wnd.vaadin.gwtStatsEvents != 'object') {
  568. $wnd.vaadin.gwtStatsEvents = [];
  569. }
  570. $wnd.__gwtStatsEvent = function(event) {
  571. $wnd.vaadin.gwtStatsEvents.push(event);
  572. return true;
  573. }
  574. }
  575. }-*/;
  576. /**
  577. * Remove logger function and event array if it seems like the function has
  578. * been added by us.
  579. */
  580. private static native void ensureNoLogger()
  581. /*-{
  582. if (typeof $wnd.vaadin.gwtStatsEvents == 'object') {
  583. delete $wnd.vaadin.gwtStatsEvents;
  584. if (typeof $wnd.__gwtStatsEvent == 'function') {
  585. $wnd.__gwtStatsEvent = function() { return true; };
  586. }
  587. }
  588. }-*/;
  589. private static native JsArray<GwtStatsEvent> clearEventsList()
  590. /*-{
  591. $wnd.vaadin.gwtStatsEvents = [];
  592. }-*/;
  593. /**
  594. * Sets the profiler result consumer that is used to output the profiler
  595. * data to the user.
  596. * <p>
  597. * <b>Warning!</b> This is internal API and should not be used by
  598. * applications or add-ons.
  599. *
  600. * @since 7.1.4
  601. * @param profilerResultConsumer
  602. * the consumer that gets profiler data
  603. */
  604. public static void setProfilerResultConsumer(
  605. ProfilerResultConsumer profilerResultConsumer) {
  606. if (consumer != null) {
  607. throw new IllegalStateException("The consumer has already been set");
  608. }
  609. consumer = profilerResultConsumer;
  610. }
  611. private static ProfilerResultConsumer getConsumer() {
  612. return consumer;
  613. }
  614. private static Logger getLogger() {
  615. return Logger.getLogger(Profiler.class.getName());
  616. }
  617. private static native boolean hasHighPrecisionTime()
  618. /*-{
  619. return $wnd.performance && (typeof $wnd.performance.now == 'function');
  620. }-*/;
  621. private interface RelativeTimeSupplier {
  622. double getRelativeTime();
  623. }
  624. private static class DefaultRelativeTimeSupplier implements
  625. RelativeTimeSupplier {
  626. @Override
  627. public native double getRelativeTime()
  628. /*-{
  629. return (new Date).getTime();
  630. }-*/;
  631. }
  632. private static class HighResolutionTimeSupplier implements
  633. RelativeTimeSupplier {
  634. @Override
  635. public native double getRelativeTime()
  636. /*-{
  637. return $wnd.performance.now();
  638. }-*/;
  639. }
  640. }