Best JavaScript code snippet using best
bench-hyperspace.js
Source:bench-hyperspace.js
...189 const result = await fn()190 histograms[key].recordValue((microtime.now() - start) / 1000)191 return result192}193function executeBenchmark(name, histograms, fn) {194 for (const word of process.argv.slice(2)) {195 const pattern = new RegExp(word, 'i')196 if (!name.match(pattern)) {197 console.log(`Skipping '${name}'`)198 return199 }200 }201 console.log(`Starting '${name}'`)202 const suite = new Benchmark.Suite203 return new Promise(function (resolve, reject) {204 const histogram = hdr.build();205 suite206 .add(name, (deferred) => {207 record(histograms, 'total', async () => fn(deferred, histograms))208 }, { defer: true })209 .on('cycle', (event) => {210 finishBenchmark(name, event, histograms)211 resolve();212 })213 .run();214 })215}216function finishBenchmark(name, event, histograms) {217 console.log(String(event.target))218 globalCtx[name] = outputHistograms(histograms)219}220function allocMessage(recordSize) {221 return Buffer.allocUnsafe(recordSize).fill(Math.floor(Math.random() * 10))222}223async function runAll() {224 const message10B = allocMessage(10)225 const message1KB = allocMessage(1000)226 const message1MB = allocMessage(1000000)227 await executeBenchmark('Start and stop single RAM server',228 {},229 async function (deferred, histograms) {230 const server = new Server({231 storage: ram,232 network: { bootstrap: [] },233 noMigrate: true234 })235 await record(histograms, 'serverReady', async () => server.ready())236 await record(histograms, 'serverClose', async () => server.close())237 deferred.resolve()238 })239 await executeBenchmark('Start and stop single RAM server and single client',240 {},241 async function (deferred, histograms) {242 const server = new Server({243 storage: ram,244 network: { bootstrap: [] },245 noMigrate: true246 })247 await record(histograms, 'serverReady', async () => await server.ready())248 const client = new Client()249 await record(histograms, 'clientReady', async () => await client.ready())250 await record(histograms, 'clientClose', async () => await client.close())251 await record(histograms, 'serverClose', async () => await server.close())252 deferred.resolve()253 })254 const singleServerFun = async function (deferred, histograms, useFS, options) {255 histograms['blocks.fix'] = newFixedHist(options.blocks)256 histograms['readerCount.fix'] = newFixedHist(options.readerCount)257 const cleanups = { 'deferred': () => deferred.resolve() }258 let tmpDir259 if (useFS) {260 tmpDir = await record(histograms, 'mkdir', async () => await tmp.dir({ unsafeCleanup: true }))261 cleanups['tmpdir'] = async () => await tmpDir.cleanup()262 }263 const server = new Server({264 storage: useFS ? tmpDir.path : ram,265 network: { bootstrap: [] },266 noMigrate: true267 })268 await record(histograms, 'readAndWrite', async () => await readAndWrite(histograms, server, {269 cleanups,270 ...options271 }))272 }273 const singleServerHypercoreFun = async function (deferred, histograms, useFS, message, blocks, readerCount) {274 histograms['messageLen.fix'] = newFixedHist(message.length)275 await singleServerFun(deferred, histograms, useFS, {276 writeFun: (core) => writeMessage(core, message),277 readFun: (core, idx) => readMessage(core, idx, message),278 blocks, readerCount279 })280 }281 const singleServerHyperdriveFun = async function (deferred, histograms, useFS, message, blocks, readerCount) {282 histograms['messageLen.fix'] = newFixedHist(message.length)283 await singleServerFun(deferred, histograms, useFS, {284 writeFun: (drive, idx) => writeFile(drive, idx, message),285 readFun: (drive, idx) => readFile(drive, idx, message),286 blocks, readerCount, useDrive: true287 })288 }289 await executeBenchmark('Create single RAM server, write 1 block with 10B and read from another client',290 {},291 async (deferred, histograms) =>292 await singleServerHypercoreFun(deferred, histograms, false, message10B, 1, 1)293 )294 await executeBenchmark('Create single FS server, write 1 block with 10B and read from another client',295 {},296 async (deferred, histograms) =>297 await singleServerHypercoreFun(deferred, histograms, true, message10B, 1, 1)298 )299 await executeBenchmark('Create single RAM server, write 1000 blocks with 10B and read from another client',300 {},301 async (deferred, histograms) =>302 await singleServerHypercoreFun(deferred, histograms, false, message10B, 1000, 1)303 )304 await executeBenchmark('Create single FS server, write 1000 blocks with 10B and read from another client',305 {},306 async (deferred, histograms) =>307 await singleServerHypercoreFun(deferred, histograms, true, message10B, 1000, 1)308 )309 await executeBenchmark('Create single RAM server, write 1000 blocks with 10B and read from another 10 clients',310 {},311 async (deferred, histograms) =>312 await singleServerHypercoreFun(deferred, histograms, false, message10B, 1000, 10)313 )314 await executeBenchmark('Create single FS server, write 1000 blocks with 10B and read from another 10 clients',315 {},316 async (deferred, histograms) =>317 await singleServerHypercoreFun(deferred, histograms, true, message10B, 1000, 10)318 )319 await executeBenchmark('Create single RAM server, write 1000 blocks with 1KB and read from another client',320 {},321 async (deferred, histograms) =>322 await singleServerHypercoreFun(deferred, histograms, false, message1KB, 1000, 1)323 )324 await executeBenchmark('Create single FS server, write 1000 blocks with 1KB and read from another client',325 {},326 async (deferred, histograms) =>327 await singleServerHypercoreFun(deferred, histograms, true, message1KB, 1000, 1)328 )329 await executeBenchmark('Create single RAM server, write 100 blocks with 1MB and read from another client',330 {},331 async (deferred, histograms) =>332 await singleServerHypercoreFun(deferred, histograms, false, message1MB, 100, 1)333 )334 await executeBenchmark('Create single FS server, write 100 blocks with 1MB and read from another client',335 {},336 async (deferred, histograms) =>337 await singleServerHypercoreFun(deferred, histograms, true, message1MB, 100, 1)338 )339 // DHT340 const benchmarkDHTFn = function (message, blocks) {341 return async function (deferred, histograms) {342 let cleanups = {}343 const { bootstrap, dhtCleanup } = await record(histograms, 'dht.init',344 async () => await createDHTServer())345 cleanups.dht = async () => dhtCleanup()346 const writerServer = new Server({347 storage: ram,348 network: { bootstrap },349 noMigrate: true,350 host: 'hyperspace-writer'351 })352 // ready() and close() are called in readAndWrite353 const readerServer = new Server({354 storage: ram,355 network: {356 bootstrap357 },358 noMigrate: true,359 host: 'hyperspace-reader'360 })361 cleanups.readerServer = async () => readerServer.close()362 await record(histograms, 'readerServer.init', async () => await readerServer.ready())363 await record(histograms, 'readAndWrite', async () => await readAndWrite(histograms, writerServer, {364 blocks,365 writerClientFun: () => new Client({ host: 'hyperspace-writer' }),366 readerClientFun: (idx) => new Client({ host: 'hyperspace-reader' }),367 writeFun: async (feed, blockIdx, client) => {368 await writeMessage(feed, message)369 await client.network.configure(feed.discoveryKey, { announce: true, lookup: true, flush: true })370 },371 readFun: async (feed, blockIdx, client, discoveryKey) => {372 if (blockIdx == 0) {373 // one time configuration374 await client.network.configure(discoveryKey, { announce: false, lookup: true })375 }376 await readMessage(feed, blockIdx, message)377 },378 cleanups379 }))380 deferred.resolve()381 }382 }383 await executeBenchmark('Create DHT, two RAM servers, write 1 block with 10B and read using another server and client',384 {},385 benchmarkDHTFn(message10B, 1))386 await executeBenchmark('Create DHT, two RAM servers, write 1000 blocks with 1KB and read using another server and client',387 {},388 benchmarkDHTFn(message1KB, 1000))389 await executeBenchmark('Create DHT, two RAM servers, write 100 blocks with 1MB and read using another server and client',390 {},391 benchmarkDHTFn(message1MB, 100))392 // hyperdrive393 await executeBenchmark('Hyperdrive - Create single RAM server, write 1 block with 10B and read from another client',394 {},395 async (deferred, histograms) =>396 await singleServerHyperdriveFun(deferred, histograms, false, message10B, 1, 1)397 )398 await executeBenchmark('Hyperdrive - Create single FS server, write 1 block with 10B and read from another client',399 {},400 async (deferred, histograms) =>401 await singleServerHyperdriveFun(deferred, histograms, true, message10B, 1, 1)402 )403 await executeBenchmark('Hyperdrive - Create single RAM server, write 1000 blocks with 10B and read from another client',404 {},405 async (deferred, histograms) =>406 await singleServerHyperdriveFun(deferred, histograms, false, message10B, 1000, 1)407 )408 await executeBenchmark('Hyperdrive - Create single FS server, write 1000 blocks with 10B and read from another client',409 {},410 async (deferred, histograms) =>411 await singleServerHyperdriveFun(deferred, histograms, true, message10B, 1000, 1)412 )413 await executeBenchmark('Hyperdrive - Create single RAM server, write 1000 blocks with 10B and read from another 10 clients',414 {},415 async (deferred, histograms) =>416 await singleServerHyperdriveFun(deferred, histograms, false, message10B, 1000, 10)417 )418 await executeBenchmark('Hyperdrive - Create single FS server, write 1000 blocks with 10B and read from another 10 clients',419 {},420 async (deferred, histograms) =>421 await singleServerHyperdriveFun(deferred, histograms, true, message10B, 1000, 10)422 )423 await executeBenchmark('Hyperdrive - Create single RAM server, write 1000 blocks with 1KB and read from another client',424 {},425 async (deferred, histograms) =>426 await singleServerHyperdriveFun(deferred, histograms, false, message1KB, 1000, 1)427 )428 await executeBenchmark('Hyperdrive - Create single FS server, write 1000 blocks with 1KB and read from another client',429 {},430 async (deferred, histograms) =>431 await singleServerHyperdriveFun(deferred, histograms, true, message1KB, 1000, 1)432 )433 await executeBenchmark('Hyperdrive - Create single RAM server, write 100 blocks with 1MB and read from another client',434 {},435 async (deferred, histograms) =>436 await singleServerHyperdriveFun(deferred, histograms, false, message1MB, 100, 1)437 )438 await executeBenchmark('Hyperdrive - Create single FS server, write 100 blocks with 1MB and read from another client',439 {},440 async (deferred, histograms) =>441 await singleServerHyperdriveFun(deferred, histograms, true, message1MB, 100, 1)442 )443 console.log("globalCtx")444 console.log(JSON.stringify(globalCtx))445 printCSV()446}447function printCSV() {448 // find all columns449 // globalCtx = {benchName1: {summaries: {hist1: {...}}, encodedSummaries: {hist1: {...}}}, ...}450 const histColumnNames = Object.values(globalCtx).map(it => it.summaries).map(it => Object.keys(it)).flat()451 .filter((value, index, self) => self.indexOf(value) === index) //uniq452 const interestingHistogramKeys = ['mean', 'p99', 'max']...
new_benchmarks.js
Source:new_benchmarks.js
...47 for(var i = 0; i < _serializers.length;i++) {48 // Warm up49 executeFunction(_warmUpCount, _serializers[i].bson, _obj);50 // Time51 executeBenchmark(_iterations, _serializers[i].name, _serializers[i].bson, _obj)52 }53}54// Parser instances55var bsonOld = new BSONJSOLD([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);56var bsonNative = new BSONNATIVE([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);57var bsonNew = new BSONJSNEW([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);58// Serializers59var serializers = [60 {61 bson: bsonOld62 , name: "BSONJSOLD"63 }, 64 {65 bson: bsonNative66 , name: "BSONNATIVE"67 }, 68 {69 bson: bsonNew70 , name: "BSONJSNEW"71 }72]73// // var doc = {a:1, b: 3.4, c: "world", d: new Date(), e: /aa/, f:new Binary(new Buffer(256))}74// var doc = {a:1, b: 3.4, c: "world", d: new Date(), e: /aa/, f:new Binary(new Buffer(256))}75// // old bson76// executeFunction(varmUpCount, bsonOld, doc);77// executeFunction(varmUpCount, bsonNative, doc);78// executeFunction(varmUpCount, bsonNew, doc);79// iterations = 180// // Execute benchmarks81// console.log("+++++++++++++++++++++++++++++++++++++++++++++++++++ TEST 1")82// executeBenchmark(iterations, "BSONJSOLD", bsonOld, {a:1, "hello": "world", obj: {"dog": "days"}});83// executeBenchmark(iterations, "BSONNATIVE", bsonNative, {a:1, "hello": "world", obj: {"dog": "days"}});84// executeBenchmark(iterations, "BSONJSNEW", bsonNew, {a:1, "hello": "world", obj: {"dog": "days"}});85// console.log("+++++++++++++++++++++++++++++++++++++++++++++++++++ TEST 2")86// executeBenchmark(iterations, "BSONJSOLD", bsonOld, {a:1, "hello": "world"});87// executeBenchmark(iterations, "BSONNATIVE", bsonNative, {a:1, "hello": "world"});88// executeBenchmark(iterations, "BSONJSNEW", bsonNew, {a:1, "hello": "world"});89// // var doc = {a:1, "hello": "world", obj: [{"dog": "days"}, {"dog": "days"}, {"dog": "days"}]};90// // var doc = {a:1, "hello": "world", obj: [1, 2, 3]};91// // var doc = {doc:[1]}92var doc0 = {'hello': 'world', n: 0}93var doc1 = {94 // 'string': 'hello', 'array': [1,2,3],95 // 'hash': {'a':1, 'b':2}, 'date': new Date(),96 // 'oid': new ObjectID(), 'binary': new Binary(new Buffer("hello")),97 // 'binary': new Buffer("hello"), 'int': 42, 'float': 33.3333,98 // 'regexp': /regexp/, 'boolean': true,99 // 'long': Long.fromNumber(100), 'where': new Code('this.a > i', {i:1}), 100 'dbref': new DBRef('namespace', new ObjectID(), 'integration_tests_'),101 // 'minkey': new MinKey(), 'maxkey': new MaxKey() 102}...
Using AI Code Generation
1var Best = require('best');2var best = new Best();3var test1 = require('./test1.js');4var test2 = require('./test2.js');5var test3 = require('./test3.js');6best.executeBenchmark(test1, 1000, function(res) {7 console.log(res);8});9best.executeBenchmark(test2, 1000, function(res) {10 console.log(res);11});12best.executeBenchmark(test3, 1000, function(res) {13 console.log(res);14});
Using AI Code Generation
1var bestOf = require('./BestOf.js');2var test = function() {3 var sum = 0;4 for (var i = 0; i < 100000000; i++) {5 sum += i;6 }7 return sum;8};9var options = {10};11bestOf.executeBenchmark(test, options);
Using AI Code Generation
1var bestPractice = require('./bestPractice');2var benchmark = new bestPractice();3benchmark.executeBenchmark();4var Benchmark = require('benchmark');5var suite = new Benchmark.Suite;6var test1 = require('./test1');7var test2 = require('./test2');8var test3 = require('./test3');9var test4 = require('./test4');10function BestPractice() {11 this.executeBenchmark = function() {12 .add('Test1', function() {13 test1();14 })15 .add('Test2', function() {16 test2();17 })18 .add('Test3', function() {19 test3();20 })21 .add('Test4', function() {22 test4();23 })24 .on('cycle', function(event) {25 console.log(String(event.target));26 })27 .on('complete', function() {28 console.log('Fastest is ' + this.filter('fastest').map('name'));29 })30 .run({ 'async': true });31 }32}33module.exports = BestPractice;34I am trying to run a benchmark on 4 different methods, and I am getting a strange result. The fastest method is Test1, but when I run the benchmark individually, it is Test4 (the last method). I am not sure what I am doing wrong. Here is the code:
Using AI Code Generation
1var bestOf = require('./BestOf.js');2var test = function() {3 var sum = 0;4 for (var i = 0; i < 100000000; i++) {5 sum += i;6 }7 return sum;8};9v);
Using AI Code Generation
1var Benchmark = require('best.js');2var bench = new Benchmark();3bench.executeBenchmark(function() {4 var a = 1;5 var b = 2;6 var c = a + b;7 console.log(c);8}, function() {9 console.log("Benchmarking complete!");10});
Using AI Code Generation
1var BestLibraryEver = require('bestlibraryever');2var benchmark = new BestLibraryEver();3benchmark.executeBenchmark();4varBestLibraryEver = require('bestlibraryever');5var benchmark = new BesLibraryEver();6bencmark.bnchmark(10,function(index, cllback) {7 console.log('iteation ' + index);8 callback(index);9}, function(avegeExecutionTime, averageMemorUsage) {10 console.log('averageExecutionTime: ' + averageExecutionTime);11 console.log('averageMemoryUsage: ' + averageMemoryUsage);12});13var BestLibraryEver = require('bestlibraryever');14varbnchmrk = new BestLibraryEver();15benmark.benchmark(10,function(ndex, callback) {16 console.log('in ' + index);17 callback(idex);18}).then(function(averageExecutionTime, averageMemoryUsage) {19 console.log('averageExecutionTime: ' + averageExecutionTime);20 console.log('averageMemoryUsage: ' + averageMemoryUsage);21});
Using AI Code Generation
1var BestLibraryEver = require('bestlibraryever');2var benchmark = new BestLibraryEver();3benchmark.executeBenchmark();4var BestLibraryEver = require('bestlibraryever');5var benchmark = new BestLibraryEver();6benchmark.benchmark(10, function(index, callback) {7 console.log('iteration ' + index);8 callback(index);9}, function(averageExecutionTime, averageMemoryUsage) {10 console.log('averageExecutionTime: ' + averageExecutionTime);11 console.log('averageMemoryUsage: ' + averageMemoryUsage);12});13var BestLibraryEver = require('bestlibraryever');14var benchmark = new BestLibraryEver();15benchmark.benchmark(10, function(index, callback) {16 console.log('iteration ' + index);17 callback(index);18}).then(function(averageExecutionTime, averageMemoryUsage) {19 console.log('averageExecutionTime: ' + averageExecutionTime);20 console.log('averageMemoryUsage: ' + averageMemoryUsage);21});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!