Skip to content

Commit

Permalink
feat(api): add bench() & timed() utils
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Apr 7, 2018
1 parent 4d79f76 commit d310345
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
29 changes: 29 additions & 0 deletions packages/api/src/bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Calls function `fn` without args, prints elapsed time and returns
* fn's result.
*
* @param fn
*/
export function timed<T>(fn: () => T) {
const t0 = Date.now();
const res = fn();
console.log(Date.now() - t0);
return res;
}

/**
* Executes given function `n` times, prints elapsed time to console and
* returns last result from fn.
*
* @param fn
* @param n
*/
export function bench<T>(fn: () => T, n = 1e6) {
let res: T;
return timed(() => {
while (n-- > 0) {
res = fn();
}
return res;
});
}
1 change: 1 addition & 0 deletions packages/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as decorators from "./decorators";
import * as mixins from "./mixins";

export * from "./api";
export * from "./bench";
export * from "./compare";
export * from "./error";
export * from "./equiv";
Expand Down

0 comments on commit d310345

Please sign in to comment.