npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@stdlib/utils-timeit

v0.2.3

Published

Time a snippet.

Downloads

11

Readme

timeit

NPM version Build Status Coverage Status

Time a snippet.

Installation

npm install @stdlib/utils-timeit

Usage

var timeit = require( '@stdlib/utils-timeit' );

timeit( code, [options,] clbk )

Times a snippet.

var code = 'var x = Math.pow( Math.random(), 3 );';
code += 'if ( x !== x ) {';
code += 'throw new Error( \'Something went wrong.\' );';
code += '}';

timeit( code, done );

function done( error, results ) {
    if ( error ) {
        throw error;
    }
    console.dir( results );
    /* e.g., =>
        {
            'iterations': 1000000,
            'repeats': 3,
            'min': [0,135734733],       // [seconds,nanoseconds]
            'elapsed': 0.135734733,     // seconds
            'rate': 7367311.062526641,  // iterations/second
            'times': [                  // raw timing results
                [0,145641393],
                [0,135734733],
                [0,140462721]
            ]
        }
    */
}

The function supports the following options:

  • before: setup code. Default: "".
  • after: cleanup code. Default: "".
  • iterations: number of iterations. If null, the number of iterations is determined by trying successive powers of 10 until the total time is at least 0.1 seconds. Default: 1e6.
  • repeats: number of repeats. Default: 3.
  • asynchronous: boolean indicating whether a snippet is asynchronous. Default: false.

To perform any setup or initialization, provide setup code.

var setup = 'var randu = require( \'@stdlib/random-base-randu\' );';
setup += 'var pow = require( \'@stdlib/math-base-special-pow\' );';

var code = 'var x = pow( randu(), 3 );';
code += 'if ( x !== x ) {';
code += 'throw new Error( \'Something went wrong.\' );';
code += '}';

var opts = {
    'before': setup
};

timeit( code, opts, done );

function done( error, results ) {
    if ( error ) {
        throw error;
    }
    console.dir( results );
}

To perform any cleanup, provide cleanup code.

var setup = 'var randu = require( \'@stdlib/random-base-randu\' );';
setup += 'var hypot = require( \'@stdlib/math-base-special-hypot\' );';

var code = 'var h = hypot( randu()*10, randu()*10 );';
code += 'if ( h < 0 || h > 200 ) {';
code += 'throw new Error( \'Something went wrong.\' );';
code += '}';

var cleanup = 'if ( h !== h ) {';
cleanup += 'throw new Error( \'Something went wrong.\' );';
cleanup += '}';

var opts = {
    'before': setup,
    'after': cleanup
};

timeit( code, opts, done );

function done( error, results ) {
    if ( error ) {
        throw error;
    }
    console.dir( results );
}

To time an asynchronous snippet, set the asynchronous option to true.

var code = 'var x = Math.pow( Math.random(), 3 );';
code += 'if ( x !== x ) {';
code += 'var err = new Error( \'Something went wrong.\' );';
code += 'next( err );';
code += '}';
code += 'process.nextTick( next );';

var opts = {
    'iterations': 1e2,
    'asynchronous': true
};

timeit( code, opts, done );

function done( error, results ) {
    if ( error ) {
        throw error;
    }
    console.dir( results );
}

If asynchronous is true, the implementation assumes that before, after, and code snippets are all asynchronous. Accordingly, these snippets should invoke a next( [error] ) callback once complete. For example, given the following snippet,

setTimeout( done, 0 );

function done( error ) {
    if ( error ) {
        return next( error );
    }
    next();
}

the implementation wraps the snippet within a function having the following signature

function wrapped( state, next ) {
    setTimeout( done, 0 );

    function done( error ) {
        if ( error ) {
            return next( error );
        }
        next();
    }
}

The state parameter is simply an empty {} which allows the before, after, and code snippets to share state.

function before( state, next ) {
    state.counter = 0;
}

function code( state, next ) {
    setTimeout( done, 0 );

    function done( error ) {
        if ( error ) {
            return next( error );
        }
        state.counter += 1;
        next();
    }
}

function after( state, next ) {
    var err;
    if ( state.counter !== state.counter ) {
        err = new Error( 'Something went wrong!' );
        return next( err );
    }
    next();
}

Notes

  • Snippets always run in strict mode.
  • Always verify results. Doing so prevents the compiler from performing dead code elimination and other optimization techniques, which would render timing results meaningless.
  • Executed code is not sandboxed and has access to the global state. You are strongly advised against timing untrusted code. To time untrusted code, do so in an isolated environment (e.g., a separate process with restricted access to both global state and the host environment).
  • Wrapping asynchronous code does add overhead, but, in most cases, the overhead should be negligible compared to the execution cost of the timed snippet.
  • Ensure that, when asynchronous is true, the main code snippet is actually asynchronous. If a snippet releases the zalgo, an error complaining about exceeding the maximum call stack size is highly likely.
  • While many benchmark frameworks calculate various statistics over raw timing results (e.g., mean and standard deviation), do not do this. Instead, consider the fastest time an approximate lower bound for how fast an environment can execute a snippet. Slower times are more likely attributable to other processes interfering with timing accuracy rather than attributable to variability in JavaScript's speed. In which case, the minimum time is most likely the only result of interest. When considering all raw timing results, apply common sense rather than statistics.

Examples

var join = require( 'path' ).join;
var readFileSync = require( '@stdlib/fs-read-file' ).sync;
var timeit = require( '@stdlib/utils-timeit' );

var before = readFileSync( join( __dirname, 'examples', 'before.txt' ), 'utf8' );
var code = readFileSync( join( __dirname, 'examples', 'code.txt' ), 'utf8' );

var opts = {
    'iterations': 1e6,
    'repeats': 5,
    'before': before
};

timeit( code, opts, done );

function done( error, results ) {
    if ( error ) {
        throw error;
    }
    console.dir( results );
}

References

See Also


Notice

This package is part of stdlib, a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing. The library provides a collection of robust, high performance libraries for mathematics, statistics, streams, utilities, and more.

For more information on the project, filing bug reports and feature requests, and guidance on how to develop stdlib, see the main project repository.

Community

Chat


License

See LICENSE.

Copyright

Copyright © 2016-2024. The Stdlib Authors.