版博士V2.0程序
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. # tinybench
  2. Benchmark your code easily with Tinybench, a simple, tiny and light-weight `7KB` (`2KB` minified and gzipped)
  3. benchmarking library!
  4. You can run your benchmarks in multiple JavaScript runtimes, Tinybench is
  5. completely based on the Web APIs with proper timing using `process.hrtime` or
  6. `performance.now`.
  7. - Accurate and precise timing based on the environment
  8. - `Event` and `EventTarget` compatible events
  9. - Statistically analyzed values
  10. - Calculated Percentiles
  11. - Fully detailed results
  12. - No dependencies
  13. _In case you need more tiny libraries like tinypool or tinyspy, please consider submitting an [RFC](https://github.com/tinylibs/rfcs)_
  14. ## Installing
  15. ```bash
  16. $ npm install -D tinybench
  17. ```
  18. ## Usage
  19. You can start benchmarking by instantiating the `Bench` class and adding
  20. benchmark tasks to it.
  21. ```js
  22. import { Bench } from 'tinybench';
  23. const bench = new Bench({ time: 100 });
  24. bench
  25. .add('switch 1', () => {
  26. let a = 1;
  27. let b = 2;
  28. const c = a;
  29. a = b;
  30. b = c;
  31. })
  32. .add('switch 2', () => {
  33. let a = 1;
  34. let b = 10;
  35. a = b + a;
  36. b = a - b;
  37. a = b - a;
  38. });
  39. await bench.run();
  40. console.table(bench.tasks.map(({ name, result }) => ({ "Task Name": name, "Average Time (ps)": result?.mean * 1000, "Variance (ps)": result?.variance * 1000 })));
  41. // Output:
  42. // ┌─────────┬────────────┬────────────────────┬────────────────────┐
  43. // │ (index) │ Task Name │ Average Time (ps) │ Variance (ps) │
  44. // ├─────────┼────────────┼────────────────────┼────────────────────┤
  45. // │ 0 │ 'switch 1' │ 1.8458325710527104 │ 1.2113875253341617 │
  46. // │ 1 │ 'switch 2' │ 1.8746935152109603 │ 1.2254725890767446 │
  47. // └─────────┴────────────┴────────────────────┴────────────────────┘
  48. ```
  49. The `add` method accepts a task name and a task function, so it can benchmark
  50. it! This method returns a reference to the Bench instance, so it's possible to
  51. use it to create an another task for that instance.
  52. Note that the task name should always be unique in an instance, because Tinybench stores the tasks based
  53. on their names in a `Map`.
  54. Also note that `tinybench` does not log any result by default. You can extract the relevant stats
  55. from `bench.tasks` or any other API after running the benchmark, and process them however you want.
  56. ## Docs
  57. ### `Bench`
  58. The Benchmark instance for keeping track of the benchmark tasks and controlling
  59. them.
  60. Options:
  61. ```ts
  62. export type Options = {
  63. /**
  64. * time needed for running a benchmark task (milliseconds) @default 500
  65. */
  66. time?: number;
  67. /**
  68. * number of times that a task should run if even the time option is finished @default 10
  69. */
  70. iterations?: number;
  71. /**
  72. * function to get the current timestamp in milliseconds
  73. */
  74. now?: () => number;
  75. /**
  76. * An AbortSignal for aborting the benchmark
  77. */
  78. signal?: AbortSignal;
  79. /**
  80. * warmup time (milliseconds) @default 100ms
  81. */
  82. warmupTime?: number;
  83. /**
  84. * warmup iterations @default 5
  85. */
  86. warmupIterations?: number;
  87. /**
  88. * setup function to run before each benchmark task (cycle)
  89. */
  90. setup?: Hook;
  91. /**
  92. * teardown function to run after each benchmark task (cycle)
  93. */
  94. teardown?: Hook;
  95. };
  96. export type Hook = (task: Task, mode: "warmup" | "run") => void | Promise<void>;
  97. ```
  98. - `async run()`: run the added tasks that were registered using the `add` method
  99. - `async warmup()`: warm up the benchmark tasks
  100. - `reset()`: reset each task and remove its result
  101. - `add(name: string, fn: Fn, opts?: FnOpts)`: add a benchmark task to the task map
  102. - `Fn`: `() => any | Promise<any>`
  103. - `FnOpts`: `{}`: a set of optional functions run during the benchmark lifecycle that can be used to set up or tear down test data or fixtures without affecting the timing of each task
  104. - `beforeAll?: () => any | Promise<any>`: invoked once before iterations of `fn` begin
  105. - `beforeEach?: () => any | Promise<any>`: invoked before each time `fn` is executed
  106. - `afterEach?: () => any | Promise<any>`: invoked after each time `fn` is executed
  107. - `afterAll?: () => any | Promise<any>`: invoked once after all iterations of `fn` have finished
  108. - `remove(name: string)`: remove a benchmark task from the task map
  109. - `get results(): (TaskResult | undefined)[]`: (getter) tasks results as an array
  110. - `get tasks(): Task[]`: (getter) tasks as an array
  111. - `getTask(name: string): Task | undefined`: get a task based on the name
  112. ### `Task`
  113. A class that represents each benchmark task in Tinybench. It keeps track of the
  114. results, name, Bench instance, the task function and the number of times the task
  115. function has been executed.
  116. - `constructor(bench: Bench, name: string, fn: Fn, opts: FnOptions = {})`
  117. - `bench: Bench`
  118. - `name: string`: task name
  119. - `fn: Fn`: the task function
  120. - `opts: FnOptions`: Task options
  121. - `runs: number`: the number of times the task function has been executed
  122. - `result?: TaskResult`: the result object
  123. - `async run()`: run the current task and write the results in `Task.result` object
  124. - `async warmup()`: warm up the current task
  125. - `setResult(result: Partial<TaskResult>)`: change the result object values
  126. - `reset()`: reset the task to make the `Task.runs` a zero-value and remove the `Task.result` object
  127. ```ts
  128. export interface FnOptions {
  129. /**
  130. * An optional function that is run before iterations of this task begin
  131. */
  132. beforeAll?: (this: Task) => void | Promise<void>;
  133. /**
  134. * An optional function that is run before each iteration of this task
  135. */
  136. beforeEach?: (this: Task) => void | Promise<void>;
  137. /**
  138. * An optional function that is run after each iteration of this task
  139. */
  140. afterEach?: (this: Task) => void | Promise<void>;
  141. /**
  142. * An optional function that is run after all iterations of this task end
  143. */
  144. afterAll?: (this: Task) => void | Promise<void>;
  145. }
  146. ```
  147. ## `TaskResult`
  148. the benchmark task result object.
  149. ```ts
  150. export type TaskResult = {
  151. /*
  152. * the last error that was thrown while running the task
  153. */
  154. error?: unknown;
  155. /**
  156. * The amount of time in milliseconds to run the benchmark task (cycle).
  157. */
  158. totalTime: number;
  159. /**
  160. * the minimum value in the samples
  161. */
  162. min: number;
  163. /**
  164. * the maximum value in the samples
  165. */
  166. max: number;
  167. /**
  168. * the number of operations per second
  169. */
  170. hz: number;
  171. /**
  172. * how long each operation takes (ms)
  173. */
  174. period: number;
  175. /**
  176. * task samples of each task iteration time (ms)
  177. */
  178. samples: number[];
  179. /**
  180. * samples mean/average (estimate of the population mean)
  181. */
  182. mean: number;
  183. /**
  184. * samples variance (estimate of the population variance)
  185. */
  186. variance: number;
  187. /**
  188. * samples standard deviation (estimate of the population standard deviation)
  189. */
  190. sd: number;
  191. /**
  192. * standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean)
  193. */
  194. sem: number;
  195. /**
  196. * degrees of freedom
  197. */
  198. df: number;
  199. /**
  200. * critical value of the samples
  201. */
  202. critical: number;
  203. /**
  204. * margin of error
  205. */
  206. moe: number;
  207. /**
  208. * relative margin of error
  209. */
  210. rme: number;
  211. /**
  212. * p75 percentile
  213. */
  214. p75: number;
  215. /**
  216. * p99 percentile
  217. */
  218. p99: number;
  219. /**
  220. * p995 percentile
  221. */
  222. p995: number;
  223. /**
  224. * p999 percentile
  225. */
  226. p999: number;
  227. };
  228. ```
  229. ### `Events`
  230. Both the `Task` and `Bench` objects extend the `EventTarget` object, so you can attach listeners to different types of events
  231. in each class instance using the universal `addEventListener` and
  232. `removeEventListener`.
  233. ```ts
  234. /**
  235. * Bench events
  236. */
  237. export type BenchEvents =
  238. | "abort" // when a signal aborts
  239. | "complete" // when running a benchmark finishes
  240. | "error" // when the benchmark task throws
  241. | "reset" // when the reset function gets called
  242. | "start" // when running the benchmarks gets started
  243. | "warmup" // when the benchmarks start getting warmed up (before start)
  244. | "cycle" // when running each benchmark task gets done (cycle)
  245. | "add" // when a Task gets added to the Bench
  246. | "remove"; // when a Task gets removed of the Bench
  247. /**
  248. * task events
  249. */
  250. export type TaskEvents =
  251. | "abort"
  252. | "complete"
  253. | "error"
  254. | "reset"
  255. | "start"
  256. | "warmup"
  257. | "cycle";
  258. ```
  259. For instance:
  260. ```js
  261. // runs on each benchmark task's cycle
  262. bench.addEventListener("cycle", (e) => {
  263. const task = e.task!;
  264. });
  265. // runs only on this benchmark task's cycle
  266. task.addEventListener("cycle", (e) => {
  267. const task = e.task!;
  268. });
  269. ```
  270. ### `BenchEvent`
  271. ```ts
  272. export type BenchEvent = Event & {
  273. task: Task | null;
  274. };
  275. ```
  276. ## Prior art
  277. - [Benchmark.js](https://github.com/bestiejs/benchmark.js)
  278. - [Mitata](https://github.com/evanwashere/mitata/)
  279. - [Bema](https://github.com/prisma-labs/bema)
  280. ## Authors
  281. | <a href="https://github.com/Aslemammad"> <img width='150' src="https://avatars.githubusercontent.com/u/37929992?v=4" /><br> Mohammad Bagher </a> |
  282. | ------------------------------------------------------------------------------------------------------------------------------------------------ |
  283. ## Credits
  284. | <a href="https://github.com/uzploak"> <img width='150' src="https://avatars.githubusercontent.com/u/5059100?v=4" /><br> Uzlopak </a> | <a href="https://github.com/poyoho"> <img width='150' src="https://avatars.githubusercontent.com/u/36070057?v=4" /><br> poyoho </a> |
  285. | ------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
  286. ## Contributing
  287. Feel free to create issues/discussions and then PRs for the project!