File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ export function fibonacci ( num : number ) : number {
2+ if ( num <= 1 ) {
3+ return num ;
4+ }
5+
6+ return fibonacci ( num - 1 ) + fibonacci ( num - 2 ) ;
7+ }
8+
9+ export function timeFibonacci ( num : number ) : number {
10+ const start = Date . now ( ) ;
11+
12+ fibonacci ( num ) ;
13+
14+ return Date . now ( ) - start ;
15+ }
Original file line number Diff line number Diff line change 1+ /**
2+ * This file boots the worker in dev when the project is run through ts-node.
3+ * - This file is not included in the build.
4+ */
5+ if ( ! process . execArgv . includes ( 'ts-node/register' ) ) {
6+ require ( 'ts-node' ) . register ( ) ;
7+ }
8+
9+ const path = require ( 'path' ) ;
10+ require ( path . resolve ( __dirname , './index.ts' ) ) ;
Original file line number Diff line number Diff line change 1+ import { timeFibonacci } from './fibonacci' ;
2+ import { log } from './log' ;
3+ import { fibonacciQueue } from './queue' ;
4+
5+ if ( fibonacciQueue . isMainThread ( ) ) {
6+ log . info ( 'Starting main thread...' ) ;
7+
8+ const n = 30 ;
9+
10+ // Run a single fib on the main thread as a control
11+ log . info ( 'main thread took' , timeFibonacci ( n ) ) ;
12+
13+ const start = Date . now ( ) ;
14+
15+ const p1 = fibonacciQueue . await ( n )
16+ . then ( ( res : number ) => log . info ( 'First worker complete in (ms)' , res ) )
17+ . catch ( log . error ) ;
18+
19+ const p2 = fibonacciQueue . await ( n )
20+ . then ( ( res : number ) => log . info ( 'Second worker complete in (ms)' , res ) )
21+ . catch ( log . error ) ;
22+
23+ const p3 = fibonacciQueue . await ( n )
24+ . then ( ( res : number ) => log . info ( 'Third worker complete in (ms)' , res ) )
25+ . catch ( log . error ) ;
26+
27+ Promise . all ( [ p1 , p2 , p3 ] )
28+ . then ( ( ) => {
29+ const time = Date . now ( ) - start ;
30+ log . info ( 'All took (ms) ' + time ) ;
31+ } )
32+ . catch ( log . error ) ;
33+ }
Original file line number Diff line number Diff line change 1+ import { Log } from 'ts-tiny-log' ;
2+
3+ export const log = new Log ( ) ;
Original file line number Diff line number Diff line change 1+ import { Queue } from '../src' ;
2+ import { log } from './log' ;
3+ import { timeFibonacci } from './fibonacci' ;
4+
5+ /**
6+ * Worker threads
7+ */
8+ export const fibonacciQueue = new Queue < number , number > ( {
9+ name : 'fibonacci' ,
10+ workerEntry : __dirname ,
11+ nWorkers : 4 ,
12+ callback : async ( num ) => timeFibonacci ( num ) ,
13+ } ) ;
Original file line number Diff line number Diff line change 1818 " ./dist/"
1919 ],
2020 "include" : [
21+ " ./example/" ,
2122 " ./script/" ,
2223 " ./src/" ,
2324 " ./test/" ,
You can’t perform that action at this time.
0 commit comments