Javascript code for making my browser slow down

后端 未结 8 1821
野性不改
野性不改 2021-02-19 02:28

I\'m writing a library for WebWorkers, and I want to test the difference between running a script in the main page thread, versus in one or more workers. The problem is: I can\'

8条回答
  •  感情败类
    2021-02-19 02:56

    Maybe this is what you are looking for:

        var threadTest = function(durationMs, outputFkt, outputInterval) {
            var startDateTime = (new Date()).getTime();
                counter = 0,
                testDateTime = null,
                since = 0, 
                lastSince = -1;
    
            do {
                testDateTime = (new Date()).getTime();
                counter++;
    
                since = testDateTime - startDateTime;
    
                if(typeof outputFkt != 'undefined' && lastSince != since && testDateTime % outputInterval == 0) {
                    outputFkt(counter, since);
                    lastSince = since;
                }
            } while(durationMs > since);
    
            if(typeof outputFkt != 'undefined') {
                    outputFkt(counter, since);
            }
    
            return counter;
        }
    

    This method will simply repeat a check in a loop

    durationMS - duartion it should run in miliseconds
    
    OPTIONAL:
    outputFkt - a callback method, for logging purpose function(currentCount, milisecondsSinceStart)
    outputInterval - intervall the output function will be called
    

    I figured since you do not want to test a real function, and even NP-Hard Problems have a ratio between input length and time this could be a easy way. You can measure performance at any interval and of course receive the number of loops as a return value, so you can easily measure how much threads interfere each others performance, with the callback even on a per cycle basis.

    As an example here is how i called it (jQuery and Dom usage are here, but as you can see optional)

    $(document).ready(function() {
        var outputFkt = function(counter, since) {
            $('body').append('

    '+counter+', since '+since+'

    '); }; threadTest(1000, outputFkt, 20); });

    A last Warning: Of course this function can not be more exact than JS itself. Since modern Browsers can do much more than one cycle in one Milisecond, there will be a little tail that gets cut.

    Update

    Thinking about it... actually using the ouputFkt callback for more than just output could give great insight. You could pass a method that uses some shared properties, or you could use it to test great memory usage.

提交回复
热议问题