Skip to content

Instantly share code, notes, and snippets.

@FGRibreau
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FGRibreau/a80fbc29109dc945fab0 to your computer and use it in GitHub Desktop.
Save FGRibreau/a80fbc29109dc945fab0 to your computer and use it in GitHub Desktop.
student_question.js
'use strict';
/**
$node perfs.js
___________________________________________________[Bench] Generating table (size=1600000) took: 593ms
sum=816028274.8700228
avg=510.01767179376424
___________________________________________________[Bench] Calculating sum took: 78ms
___________________________________________________[Bench] Sort users by rank DESC took: 2702ms
Best score user(id=1322940, score=1010, rank=0)
Lowest score user(id=1495965, score=10, rank=0)
___________________________________________________[Bench] Update rank took: 227ms
___________________________________________________[Bench] Total runtime took: 3602ms
___________________________________________________[Bench] (bonus) sort users by id ASC took: 2596ms
First user(id=1057231, score=1010, rank=1)
Last user(id=1495965, score=10, rank=1599999)
*/
var _ = require('lodash');
var TABLE_SIZE = 1600000;
var table, sum, avg;
bench('Total runtime', function () {
bench('Generating table (size=' + TABLE_SIZE + ')', function () {
// first generate a dummy table
table = _.range(0, TABLE_SIZE).map(function (v) {
// model : [user_id, score, rank]
return [v, Math.round(1000 + Math.random() * 100000) / 100, 0]; // 0 because I don't know the current gamer rank
});
});
bench('Calculating sum', function () {
sum = table.reduce(function (a, b) {
return a + b[1];
}, 0);
avg = sum / table.length;
console.log('sum=%s', sum);
console.log('avg=%s', avg);
});
bench('Sort users by rank DESC', function () {
// .sort (mutable, edit in place) took 2644ms
// .sortBy (immutable, returns a copy) took 7747ms
table.sort(function (a, b) {
return b[1] - a[1];
});
});
print('Best score', _.first(table));
print('Lowest score', _.last(table));
bench('Update rank', function () {
// still mutable
table.forEach(function (v, rank) {
// update rank (because rank == element index)
v[2] = rank;
});
});
});
bench('(bonus) sort users by id ASC', function () {
// still mutable
table.sort(function (a, b) {
return a[0] - b[0];
});
});
print('First', _.find(table, {
2: 1
}));
print('Last', _.find(table, {
2: TABLE_SIZE - 1
}));
function print(prefix, v) {
console.log('%s user(id=%s, score=%s, rank=%s)', prefix, v[0], v[1], v[2]);
}
function bench(label, f) {
label = '___________________________________________________[Bench] ' + label + ' took';
console.time(label);
f();
console.timeEnd(label);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment