splay.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. ////////////////////////////////////////////////////////////////////////////////
  2. // base.js
  3. ////////////////////////////////////////////////////////////////////////////////
  4. // Copyright 2013 the V8 project authors. All rights reserved.
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following
  13. // disclaimer in the documentation and/or other materials provided
  14. // with the distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived
  17. // from this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. if(typeof(WScript) === "undefined")
  31. {
  32. var WScript = {
  33. Echo: print
  34. }
  35. }
  36. // Performance.now is used in latency benchmarks, the fallback is Date.now.
  37. var performance = performance || {};
  38. performance.now = (function() {
  39. return performance.now ||
  40. performance.mozNow ||
  41. performance.msNow ||
  42. performance.oNow ||
  43. performance.webkitNow ||
  44. Date.now;
  45. })();
  46. // Simple framework for running the benchmark suites and
  47. // computing a score based on the timing measurements.
  48. // A benchmark has a name (string) and a function that will be run to
  49. // do the performance measurement. The optional setup and tearDown
  50. // arguments are functions that will be invoked before and after
  51. // running the benchmark, but the running time of these functions will
  52. // not be accounted for in the benchmark score.
  53. function Benchmark(name, doWarmup, doDeterministic, deterministicIterations,
  54. run, setup, tearDown, rmsResult, minIterations) {
  55. this.name = name;
  56. this.doWarmup = doWarmup;
  57. this.doDeterministic = doDeterministic;
  58. this.deterministicIterations = deterministicIterations;
  59. this.run = run;
  60. this.Setup = setup ? setup : function() { };
  61. this.TearDown = tearDown ? tearDown : function() { };
  62. this.rmsResult = rmsResult ? rmsResult : null;
  63. this.minIterations = minIterations ? minIterations : 32;
  64. }
  65. // Benchmark results hold the benchmark and the measured time used to
  66. // run the benchmark. The benchmark score is computed later once a
  67. // full benchmark suite has run to completion. If latency is set to 0
  68. // then there is no latency score for this benchmark.
  69. function BenchmarkResult(benchmark, time, latency) {
  70. this.benchmark = benchmark;
  71. this.time = time;
  72. this.latency = latency;
  73. }
  74. // Automatically convert results to numbers. Used by the geometric
  75. // mean computation.
  76. BenchmarkResult.prototype.valueOf = function() {
  77. return this.time;
  78. }
  79. // Suites of benchmarks consist of a name and the set of benchmarks in
  80. // addition to the reference timing that the final score will be based
  81. // on. This way, all scores are relative to a reference run and higher
  82. // scores implies better performance.
  83. function BenchmarkSuite(name, reference, benchmarks) {
  84. this.name = name;
  85. this.reference = reference;
  86. this.benchmarks = benchmarks;
  87. BenchmarkSuite.suites.push(this);
  88. }
  89. // Keep track of all declared benchmark suites.
  90. BenchmarkSuite.suites = [];
  91. // Scores are not comparable across versions. Bump the version if
  92. // you're making changes that will affect that scores, e.g. if you add
  93. // a new benchmark or change an existing one.
  94. BenchmarkSuite.version = '9';
  95. // Defines global benchsuite running mode that overrides benchmark suite
  96. // behavior. Intended to be set by the benchmark driver. Undefined
  97. // values here allow a benchmark to define behaviour itself.
  98. BenchmarkSuite.config = {
  99. doWarmup: undefined,
  100. doDeterministic: undefined
  101. };
  102. // Override the alert function to throw an exception instead.
  103. alert = function(s) {
  104. throw "Alert called with argument: " + s;
  105. };
  106. // To make the benchmark results predictable, we replace Math.random
  107. // with a 100% deterministic alternative.
  108. BenchmarkSuite.ResetRNG = function() {
  109. Math.random = (function() {
  110. var seed = 49734321;
  111. return function() {
  112. // Robert Jenkins' 32 bit integer hash function.
  113. seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff;
  114. seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff;
  115. seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff;
  116. seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff;
  117. seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff;
  118. seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff;
  119. return (seed & 0xfffffff) / 0x10000000;
  120. };
  121. })();
  122. }
  123. // Runs all registered benchmark suites and optionally yields between
  124. // each individual benchmark to avoid running for too long in the
  125. // context of browsers. Once done, the final score is reported to the
  126. // runner.
  127. BenchmarkSuite.RunSuites = function(runner, skipBenchmarks) {
  128. skipBenchmarks = typeof skipBenchmarks === 'undefined' ? [] : skipBenchmarks;
  129. var continuation = null;
  130. var suites = BenchmarkSuite.suites;
  131. var length = suites.length;
  132. BenchmarkSuite.scores = [];
  133. var index = 0;
  134. function RunStep() {
  135. while (continuation || index < length) {
  136. if (continuation) {
  137. continuation = continuation();
  138. } else {
  139. var suite = suites[index++];
  140. if (runner.NotifyStart) runner.NotifyStart(suite.name);
  141. if (skipBenchmarks.indexOf(suite.name) > -1) {
  142. suite.NotifySkipped(runner);
  143. } else {
  144. continuation = suite.RunStep(runner);
  145. }
  146. }
  147. if (continuation && typeof window != 'undefined' && window.setTimeout) {
  148. window.setTimeout(RunStep, 25);
  149. return;
  150. }
  151. }
  152. // show final result
  153. if (runner.NotifyScore) {
  154. var score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores);
  155. var formatted = BenchmarkSuite.FormatScore(100 * score);
  156. runner.NotifyScore(formatted);
  157. }
  158. }
  159. RunStep();
  160. }
  161. // Counts the total number of registered benchmarks. Useful for
  162. // showing progress as a percentage.
  163. BenchmarkSuite.CountBenchmarks = function() {
  164. var result = 0;
  165. var suites = BenchmarkSuite.suites;
  166. for (var i = 0; i < suites.length; i++) {
  167. result += suites[i].benchmarks.length;
  168. }
  169. return result;
  170. }
  171. // Computes the geometric mean of a set of numbers.
  172. BenchmarkSuite.GeometricMean = function(numbers) {
  173. var log = 0;
  174. for (var i = 0; i < numbers.length; i++) {
  175. log += Math.log(numbers[i]);
  176. }
  177. return Math.pow(Math.E, log / numbers.length);
  178. }
  179. // Computes the geometric mean of a set of throughput time measurements.
  180. BenchmarkSuite.GeometricMeanTime = function(measurements) {
  181. var log = 0;
  182. for (var i = 0; i < measurements.length; i++) {
  183. log += Math.log(measurements[i].time);
  184. }
  185. return Math.pow(Math.E, log / measurements.length);
  186. }
  187. // Computes the geometric mean of a set of rms measurements.
  188. BenchmarkSuite.GeometricMeanLatency = function(measurements) {
  189. var log = 0;
  190. var hasLatencyResult = false;
  191. for (var i = 0; i < measurements.length; i++) {
  192. if (measurements[i].latency != 0) {
  193. log += Math.log(measurements[i].latency);
  194. hasLatencyResult = true;
  195. }
  196. }
  197. if (hasLatencyResult) {
  198. return Math.pow(Math.E, log / measurements.length);
  199. } else {
  200. return 0;
  201. }
  202. }
  203. // Converts a score value to a string with at least three significant
  204. // digits.
  205. BenchmarkSuite.FormatScore = function(value) {
  206. if (value > 100) {
  207. return value.toFixed(0);
  208. } else {
  209. return value.toPrecision(3);
  210. }
  211. }
  212. // Notifies the runner that we're done running a single benchmark in
  213. // the benchmark suite. This can be useful to report progress.
  214. BenchmarkSuite.prototype.NotifyStep = function(result) {
  215. this.results.push(result);
  216. if (this.runner.NotifyStep) this.runner.NotifyStep(result.benchmark.name);
  217. }
  218. // Notifies the runner that we're done with running a suite and that
  219. // we have a result which can be reported to the user if needed.
  220. BenchmarkSuite.prototype.NotifyResult = function() {
  221. var mean = BenchmarkSuite.GeometricMeanTime(this.results);
  222. var score = this.reference[0] / mean;
  223. BenchmarkSuite.scores.push(score);
  224. if (this.runner.NotifyResult) {
  225. var formatted = BenchmarkSuite.FormatScore(100 * score);
  226. this.runner.NotifyResult("### SCORE:", formatted);
  227. }
  228. if (this.reference.length == 2) {
  229. var meanLatency = BenchmarkSuite.GeometricMeanLatency(this.results);
  230. if (meanLatency != 0) {
  231. var scoreLatency = this.reference[1] / meanLatency;
  232. BenchmarkSuite.scores.push(scoreLatency);
  233. if (this.runner.NotifyResult) {
  234. var formattedLatency = BenchmarkSuite.FormatScore(100 * scoreLatency)
  235. this.runner.NotifyResult("### LATENCY:", formattedLatency);
  236. }
  237. }
  238. }
  239. }
  240. BenchmarkSuite.prototype.NotifySkipped = function(runner) {
  241. BenchmarkSuite.scores.push(1); // push default reference score.
  242. if (runner.NotifyResult) {
  243. runner.NotifyResult(this.name, "Skipped");
  244. }
  245. }
  246. // Notifies the runner that running a benchmark resulted in an error.
  247. BenchmarkSuite.prototype.NotifyError = function(error) {
  248. if (this.runner.NotifyError) {
  249. this.runner.NotifyError(this.name, error);
  250. }
  251. if (this.runner.NotifyStep) {
  252. this.runner.NotifyStep(this.name);
  253. }
  254. }
  255. // Runs a single benchmark for at least a second and computes the
  256. // average time it takes to run a single iteration.
  257. BenchmarkSuite.prototype.RunSingleBenchmark = function(benchmark, data) {
  258. var config = BenchmarkSuite.config;
  259. var doWarmup = config.doWarmup !== undefined
  260. ? config.doWarmup
  261. : benchmark.doWarmup;
  262. var doDeterministic = config.doDeterministic !== undefined
  263. ? config.doDeterministic
  264. : benchmark.doDeterministic;
  265. function Measure(data) {
  266. var elapsed = 0;
  267. var start = new Date();
  268. // Run either for 1 second or for the number of iterations specified
  269. // by minIterations, depending on the config flag doDeterministic.
  270. for (var i = 0; (doDeterministic ?
  271. i<benchmark.deterministicIterations : elapsed < 1000); i++) {
  272. benchmark.run();
  273. elapsed = new Date() - start;
  274. }
  275. if (data != null) {
  276. data.runs += i;
  277. data.elapsed += elapsed;
  278. }
  279. }
  280. // Sets up data in order to skip or not the warmup phase.
  281. if (!doWarmup && data == null) {
  282. data = { runs: 0, elapsed: 0 };
  283. }
  284. if (data == null) {
  285. Measure(null);
  286. return { runs: 0, elapsed: 0 };
  287. } else {
  288. Measure(data);
  289. // If we've run too few iterations, we continue for another second.
  290. if (data.runs < benchmark.minIterations) return data;
  291. var usec = (data.elapsed * 1000) / data.runs;
  292. var rms = (benchmark.rmsResult != null) ? benchmark.rmsResult() : 0;
  293. this.NotifyStep(new BenchmarkResult(benchmark, usec, rms));
  294. return null;
  295. }
  296. }
  297. // This function starts running a suite, but stops between each
  298. // individual benchmark in the suite and returns a continuation
  299. // function which can be invoked to run the next benchmark. Once the
  300. // last benchmark has been executed, null is returned.
  301. BenchmarkSuite.prototype.RunStep = function(runner) {
  302. BenchmarkSuite.ResetRNG();
  303. this.results = [];
  304. this.runner = runner;
  305. var length = this.benchmarks.length;
  306. var index = 0;
  307. var suite = this;
  308. var data;
  309. // Run the setup, the actual benchmark, and the tear down in three
  310. // separate steps to allow the framework to yield between any of the
  311. // steps.
  312. function RunNextSetup() {
  313. if (index < length) {
  314. try {
  315. suite.benchmarks[index].Setup();
  316. } catch (e) {
  317. suite.NotifyError(e);
  318. return null;
  319. }
  320. return RunNextBenchmark;
  321. }
  322. suite.NotifyResult();
  323. return null;
  324. }
  325. function RunNextBenchmark() {
  326. try {
  327. data = suite.RunSingleBenchmark(suite.benchmarks[index], data);
  328. } catch (e) {
  329. suite.NotifyError(e);
  330. return null;
  331. }
  332. // If data is null, we're done with this benchmark.
  333. return (data == null) ? RunNextTearDown : RunNextBenchmark();
  334. }
  335. function RunNextTearDown() {
  336. try {
  337. suite.benchmarks[index++].TearDown();
  338. } catch (e) {
  339. suite.NotifyError(e);
  340. return null;
  341. }
  342. return RunNextSetup;
  343. }
  344. // Start out running the setup.
  345. return RunNextSetup();
  346. }
  347. /////////////////////////////////////////////////////////////
  348. // splay.js
  349. /////////////////////////////////////////////////////////////
  350. // Copyright 2009 the V8 project authors. All rights reserved.
  351. // Redistribution and use in source and binary forms, with or without
  352. // modification, are permitted provided that the following conditions are
  353. // met:
  354. //
  355. // * Redistributions of source code must retain the above copyright
  356. // notice, this list of conditions and the following disclaimer.
  357. // * Redistributions in binary form must reproduce the above
  358. // copyright notice, this list of conditions and the following
  359. // disclaimer in the documentation and/or other materials provided
  360. // with the distribution.
  361. // * Neither the name of Google Inc. nor the names of its
  362. // contributors may be used to endorse or promote products derived
  363. // from this software without specific prior written permission.
  364. //
  365. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  366. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  367. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  368. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  369. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  370. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  371. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  372. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  373. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  374. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  375. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  376. // This benchmark is based on a JavaScript log processing module used
  377. // by the V8 profiler to generate execution time profiles for runs of
  378. // JavaScript applications, and it effectively measures how fast the
  379. // JavaScript engine is at allocating nodes and reclaiming the memory
  380. // used for old nodes. Because of the way splay trees work, the engine
  381. // also has to deal with a lot of changes to the large tree object
  382. // graph.
  383. var Splay = new BenchmarkSuite('Splay', [81491, 2739514], [
  384. new Benchmark("Splay", true, false, 1400,
  385. SplayRun, SplaySetup, SplayTearDown, SplayRMS)
  386. ]);
  387. // Configuration.
  388. var kSplayTreeSize = 8000;
  389. var kSplayTreeModifications = 80;
  390. var kSplayTreePayloadDepth = 5;
  391. var splayTree = null;
  392. var splaySampleTimeStart = 0.0;
  393. function GeneratePayloadTree(depth, tag) {
  394. if (depth == 0) {
  395. return {
  396. array : [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
  397. string : 'String for key ' + tag + ' in leaf node'
  398. };
  399. } else {
  400. return {
  401. left: GeneratePayloadTree(depth - 1, tag),
  402. right: GeneratePayloadTree(depth - 1, tag)
  403. };
  404. }
  405. }
  406. function GenerateKey() {
  407. // The benchmark framework guarantees that Math.random is
  408. // deterministic; see base.js.
  409. return Math.random();
  410. }
  411. var splaySamples = 0;
  412. var splaySumOfSquaredPauses = 0;
  413. function SplayRMS() {
  414. return Math.round(Math.sqrt(splaySumOfSquaredPauses / splaySamples) * 10000);
  415. }
  416. function SplayUpdateStats(time) {
  417. var pause = time - splaySampleTimeStart;
  418. splaySampleTimeStart = time;
  419. splaySamples++;
  420. splaySumOfSquaredPauses += pause * pause;
  421. }
  422. function InsertNewNode() {
  423. // Insert new node with a unique key.
  424. var key;
  425. do {
  426. key = GenerateKey();
  427. } while (splayTree.find(key) != null);
  428. var payload = GeneratePayloadTree(kSplayTreePayloadDepth, String(key));
  429. splayTree.insert(key, payload);
  430. return key;
  431. }
  432. function SplaySetup() {
  433. // Check if the platform has the performance.now high resolution timer.
  434. // If not, throw exception and quit.
  435. if (!performance.now) {
  436. throw "PerformanceNowUnsupported";
  437. }
  438. splayTree = new SplayTree();
  439. splaySampleTimeStart = performance.now()
  440. for (var i = 0; i < kSplayTreeSize; i++) {
  441. InsertNewNode();
  442. if ((i+1) % 20 == 19) {
  443. SplayUpdateStats(performance.now());
  444. }
  445. }
  446. }
  447. function SplayTearDown() {
  448. // Allow the garbage collector to reclaim the memory
  449. // used by the splay tree no matter how we exit the
  450. // tear down function.
  451. var keys = splayTree.exportKeys();
  452. splayTree = null;
  453. splaySamples = 0;
  454. splaySumOfSquaredPauses = 0;
  455. // Verify that the splay tree has the right size.
  456. var length = keys.length;
  457. if (length != kSplayTreeSize) {
  458. throw new Error("Splay tree has wrong size");
  459. }
  460. // Verify that the splay tree has sorted, unique keys.
  461. for (var i = 0; i < length - 1; i++) {
  462. if (keys[i] >= keys[i + 1]) {
  463. throw new Error("Splay tree not sorted");
  464. }
  465. }
  466. }
  467. function SplayRun() {
  468. // Replace a few nodes in the splay tree.
  469. for (var i = 0; i < kSplayTreeModifications; i++) {
  470. var key = InsertNewNode();
  471. var greatest = splayTree.findGreatestLessThan(key);
  472. if (greatest == null) splayTree.remove(key);
  473. else splayTree.remove(greatest.key);
  474. }
  475. SplayUpdateStats(performance.now());
  476. }
  477. /**
  478. * Constructs a Splay tree. A splay tree is a self-balancing binary
  479. * search tree with the additional property that recently accessed
  480. * elements are quick to access again. It performs basic operations
  481. * such as insertion, look-up and removal in O(log(n)) amortized time.
  482. *
  483. * @constructor
  484. */
  485. function SplayTree() {
  486. };
  487. /**
  488. * Pointer to the root node of the tree.
  489. *
  490. * @type {SplayTree.Node}
  491. * @private
  492. */
  493. SplayTree.prototype.root_ = null;
  494. /**
  495. * @return {boolean} Whether the tree is empty.
  496. */
  497. SplayTree.prototype.isEmpty = function() {
  498. return !this.root_;
  499. };
  500. /**
  501. * Inserts a node into the tree with the specified key and value if
  502. * the tree does not already contain a node with the specified key. If
  503. * the value is inserted, it becomes the root of the tree.
  504. *
  505. * @param {number} key Key to insert into the tree.
  506. * @param {*} value Value to insert into the tree.
  507. */
  508. SplayTree.prototype.insert = function(key, value) {
  509. if (this.isEmpty()) {
  510. this.root_ = new SplayTree.Node(key, value);
  511. return;
  512. }
  513. // Splay on the key to move the last node on the search path for
  514. // the key to the root of the tree.
  515. this.splay_(key);
  516. if (this.root_.key == key) {
  517. return;
  518. }
  519. var node = new SplayTree.Node(key, value);
  520. if (key > this.root_.key) {
  521. node.left = this.root_;
  522. node.right = this.root_.right;
  523. this.root_.right = null;
  524. } else {
  525. node.right = this.root_;
  526. node.left = this.root_.left;
  527. this.root_.left = null;
  528. }
  529. this.root_ = node;
  530. };
  531. /**
  532. * Removes a node with the specified key from the tree if the tree
  533. * contains a node with this key. The removed node is returned. If the
  534. * key is not found, an exception is thrown.
  535. *
  536. * @param {number} key Key to find and remove from the tree.
  537. * @return {SplayTree.Node} The removed node.
  538. */
  539. SplayTree.prototype.remove = function(key) {
  540. if (this.isEmpty()) {
  541. throw Error('Key not found: ' + key);
  542. }
  543. this.splay_(key);
  544. if (this.root_.key != key) {
  545. throw Error('Key not found: ' + key);
  546. }
  547. var removed = this.root_;
  548. if (!this.root_.left) {
  549. this.root_ = this.root_.right;
  550. } else {
  551. var right = this.root_.right;
  552. this.root_ = this.root_.left;
  553. // Splay to make sure that the new root has an empty right child.
  554. this.splay_(key);
  555. // Insert the original right child as the right child of the new
  556. // root.
  557. this.root_.right = right;
  558. }
  559. return removed;
  560. };
  561. /**
  562. * Returns the node having the specified key or null if the tree doesn't contain
  563. * a node with the specified key.
  564. *
  565. * @param {number} key Key to find in the tree.
  566. * @return {SplayTree.Node} Node having the specified key.
  567. */
  568. SplayTree.prototype.find = function(key) {
  569. if (this.isEmpty()) {
  570. return null;
  571. }
  572. this.splay_(key);
  573. return this.root_.key == key ? this.root_ : null;
  574. };
  575. /**
  576. * @return {SplayTree.Node} Node having the maximum key value.
  577. */
  578. SplayTree.prototype.findMax = function(opt_startNode) {
  579. if (this.isEmpty()) {
  580. return null;
  581. }
  582. var current = opt_startNode || this.root_;
  583. while (current.right) {
  584. current = current.right;
  585. }
  586. return current;
  587. };
  588. /**
  589. * @return {SplayTree.Node} Node having the maximum key value that
  590. * is less than the specified key value.
  591. */
  592. SplayTree.prototype.findGreatestLessThan = function(key) {
  593. if (this.isEmpty()) {
  594. return null;
  595. }
  596. // Splay on the key to move the node with the given key or the last
  597. // node on the search path to the top of the tree.
  598. this.splay_(key);
  599. // Now the result is either the root node or the greatest node in
  600. // the left subtree.
  601. if (this.root_.key < key) {
  602. return this.root_;
  603. } else if (this.root_.left) {
  604. return this.findMax(this.root_.left);
  605. } else {
  606. return null;
  607. }
  608. };
  609. /**
  610. * @return {Array<*>} An array containing all the keys of tree's nodes.
  611. */
  612. SplayTree.prototype.exportKeys = function() {
  613. var result = [];
  614. if (!this.isEmpty()) {
  615. this.root_.traverse_(function(node) { result.push(node.key); });
  616. }
  617. return result;
  618. };
  619. /**
  620. * Perform the splay operation for the given key. Moves the node with
  621. * the given key to the top of the tree. If no node has the given
  622. * key, the last node on the search path is moved to the top of the
  623. * tree. This is the simplified top-down splaying algorithm from:
  624. * "Self-adjusting Binary Search Trees" by Sleator and Tarjan
  625. *
  626. * @param {number} key Key to splay the tree on.
  627. * @private
  628. */
  629. SplayTree.prototype.splay_ = function(key) {
  630. if (this.isEmpty()) {
  631. return;
  632. }
  633. // Create a dummy node. The use of the dummy node is a bit
  634. // counter-intuitive: The right child of the dummy node will hold
  635. // the L tree of the algorithm. The left child of the dummy node
  636. // will hold the R tree of the algorithm. Using a dummy node, left
  637. // and right will always be nodes and we avoid special cases.
  638. var dummy, left, right;
  639. dummy = left = right = new SplayTree.Node(null, null);
  640. var current = this.root_;
  641. while (true) {
  642. if (key < current.key) {
  643. if (!current.left) {
  644. break;
  645. }
  646. if (key < current.left.key) {
  647. // Rotate right.
  648. var tmp = current.left;
  649. current.left = tmp.right;
  650. tmp.right = current;
  651. current = tmp;
  652. if (!current.left) {
  653. break;
  654. }
  655. }
  656. // Link right.
  657. right.left = current;
  658. right = current;
  659. current = current.left;
  660. } else if (key > current.key) {
  661. if (!current.right) {
  662. break;
  663. }
  664. if (key > current.right.key) {
  665. // Rotate left.
  666. var tmp = current.right;
  667. current.right = tmp.left;
  668. tmp.left = current;
  669. current = tmp;
  670. if (!current.right) {
  671. break;
  672. }
  673. }
  674. // Link left.
  675. left.right = current;
  676. left = current;
  677. current = current.right;
  678. } else {
  679. break;
  680. }
  681. }
  682. // Assemble.
  683. left.right = current.left;
  684. right.left = current.right;
  685. current.left = dummy.right;
  686. current.right = dummy.left;
  687. this.root_ = current;
  688. };
  689. /**
  690. * Constructs a Splay tree node.
  691. *
  692. * @param {number} key Key.
  693. * @param {*} value Value.
  694. */
  695. SplayTree.Node = function(key, value) {
  696. this.key = key;
  697. this.value = value;
  698. };
  699. /**
  700. * @type {SplayTree.Node}
  701. */
  702. SplayTree.Node.prototype.left = null;
  703. /**
  704. * @type {SplayTree.Node}
  705. */
  706. SplayTree.Node.prototype.right = null;
  707. /**
  708. * Performs an ordered traversal of the subtree starting at
  709. * this SplayTree.Node.
  710. *
  711. * @param {function(SplayTree.Node)} f Visitor function.
  712. * @private
  713. */
  714. SplayTree.Node.prototype.traverse_ = function(f) {
  715. var current = this;
  716. while (current) {
  717. var left = current.left;
  718. if (left) left.traverse_(f);
  719. f(current);
  720. current = current.right;
  721. }
  722. };
  723. ////////////////////////////////////////////////////////////////////////////////
  724. // Runner
  725. ////////////////////////////////////////////////////////////////////////////////
  726. var success = true;
  727. function NotifyStart(name) {
  728. }
  729. function NotifyError(name, error) {
  730. WScript.Echo(name + " : ERROR : " +error.stack);
  731. success = false;
  732. }
  733. function NotifyResult(name, score) {
  734. if (success) {
  735. WScript.Echo(name, score);
  736. }
  737. }
  738. function NotifyScore(score) {
  739. }
  740. BenchmarkSuite.RunSuites({
  741. NotifyStart : NotifyStart,
  742. NotifyError : NotifyError,
  743. NotifyResult : NotifyResult,
  744. NotifyScore : NotifyScore
  745. });