1

I want to use Js to calculate the running time of my function, but it seems only the first time the time interval is not zero.

var i = 0;
//var timeArray = new Array();
//var date1;
//var date2;
var time = 0;
while(i < 5) {
    var date1 = new Date();
    var date2 = new Date();
    var t = decide_class(attr[i]);
    time += (date2.getTime() - date1.getTime());
    i++;
}

The attr is two dimension array and I am sure the decide_class function execute every loop.

Balthazar
  • 33,765
  • 10
  • 77
  • 104
Smilecrazy
  • 17
  • 1
  • 4

5 Answers5

1

You need to use high precision timers. The following is not completely my code.

window["performance"] = window.performance || {};
performance.now = (function() {
    return performance.now    ||
    performance.webkitNow     ||
    performance.msNow         ||
    performance.oNow          ||
    performance.mozNow        ||
    function() { return new Date().getTime(); };
})();

instead of using date.getTime() just use performance.now();

Hedzer
  • 89
  • 6
0

If you need something more accurate than date (which is milliseconds) and you're using a modern browser you can try Performance.now(): https://developer.mozilla.org/en-US/docs/Web/API/Performance.now().

Browsers: http://caniuse.com/#feat=high-resolution-time

Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.

Jorg
  • 6,881
  • 3
  • 38
  • 61
  • the outcome is still the same. I guess maybe after the first loop sth optimize the function so that the running time is greatly decreased. I try to loop for about 100000 times and record time out of while loop, it totally cost 4 seconds. – Smilecrazy Mar 25 '14 at 14:53
  • In that case you also know that the average run time of the function in the loop is 4 / 100000 seconds. Why bother calculating it *in* the while loop? – Jorg Mar 25 '14 at 22:48
0

Try using new Date.getTime() instead of just using Date(). Date.getTime() returns the number of milliseconds since midnight of January 1, 1970. Also, I don't see the point of getting new Date objects inside the loop, unless you have a specific reason for the same. Why not just call Date.getTime() before the loop entry and then again after the loop exit and find the difference to calculate how long it took for n calls of your function? (If I'm missing the reasoning behind doing it in the loop, I apologize).

0

What about calculating all the loop?

var i = 0;
//var timeArray = new Array();
//var date1;
//var date2;
var date1 = Date.now();
alert(date1)
while(i < 5) {    
    var t = decide_class(attr[i]);   
    i++;
}
var date2 = Date.now();
var time = (date2-date1);

This could help to eliminate some imprecision if the method decide_class is too fast. If even then you are getting a 0 value for time, try to evaluate if your decide_class function isn't too fast. Try something like this JavaScript sleep/wait before continuing and evaluate the value returned in time.

Community
  • 1
  • 1
Raphael do Vale
  • 841
  • 2
  • 11
  • 26
0

Two years later and your browser most likely supports performance.now(). To answer the question at hand, how to calculate the average time it takes for a function or code snippet to execute, what I do in the absence of jsPerf is create a test object containing the individual tests I'd like to measure. I then run each test 11 times, recording the last 10 measurements (the first test run acts as a warmup since I notice its time is usually skewed higher). Finally, I divide by 10 to get the average time.

Here's the code:

// Test setup (code shared by all tests)
var date = new Date()

function startTests() {
  var sOutput = '';
  
  // Define tests
  var oTestSuite = {
    'toString': function(bWarmup) {
      return doTest(function() {
        // Insert code to test below
        // ******************************************************************
        date.toString().split(' ');
        // ******************************************************************
        // End code block
      });
    },
    'concatenate': function(bWarmup) {
      return doTest(function() {
        // Insert code to test below
        // ******************************************************************
        (''+date).split(' ');
        // ******************************************************************
        // End code block
      });
    }
  };

  for (test in oTestSuite) {
    var nTestCount = 10,
      sTotalTime = test + 'Total';
    sOutput += 'Start timing \'' + test + '\' method...\n';
    oTestSuite[sTotalTime] = 0;
    oTestSuite[test](); // Warmup
    for (var i=0; i<nTestCount; ++i) {
      var nTime = oTestSuite[test]();
      oTestSuite[sTotalTime] += nTime;
      sOutput += 'Took: ' + nTime + ' ms\n';
    }
    sOutput += test + ' AVERAGE: ' + (oTestSuite[sTotalTime]/nTestCount) +
      '\n#################################################################\n';
  }
  
  document.getElementById('output').value = sOutput;
}

function doTest(fn) {
  var nStart = performance.now();
  for (var i=0, imax=100000; i<imax; ++i) {
    fn();
  }
  var nStop = performance.now(),
    nTime = nStop-nStart;
  return nTime;
}
<textarea id="output" cols="80" rows="26"></textarea><br>
<button id="btn" onclick="startTests()">Start Tests</button>

Here are the results comparing two string conversion techniques in my Chrome v50 (64-bit):

Start timing 'toString' method...
Took: 204.59500000000003 ms
Took: 210.59000000000003 ms
Took: 205.95500000000004 ms
Took: 206.57000000000005 ms
Took: 204.07500000000005 ms
Took: 205.11000000000013 ms
Took: 203.99500000000012 ms
Took: 213.87500000000023 ms
Took: 222.48499999999967 ms
Took: 206.39499999999998 ms
toString AVERAGE: 208.36450000000005
#################################################################
Start timing 'concatenate' method...
Took: 286.18499999999995 ms
Took: 283.6400000000003 ms
Took: 284.8199999999997 ms
Took: 278.5100000000002 ms
Took: 283.0750000000003 ms
Took: 282.5049999999992 ms
Took: 281.3750000000009 ms
Took: 286.59000000000106 ms
Took: 281.3150000000005 ms
Took: 284.09500000000025 ms
concatenate AVERAGE: 283.21100000000024
#################################################################

You can also play around with it in this pen: http://codepen.io/thdoan/pen/aNKJbQ

thdoan
  • 15,024
  • 1
  • 46
  • 40