2

A little about the task:
I have a function (js) that takes an argument and returns a value calculated by a mathematical formula

var f = function(x) {
    return 3 * Math.sin(2 * x) * Math.pow(Math.cos(x), 4);
}

I also have an array, the index is the interval number (indexing from scratch), the element value by index is the number of times the value fell into this index.

For example, if I have 2 elements in the array, and the values ​​that interest me are from 0 to 1, then if f (x) returned a number less than 0.5, then the first element of the array increases by 1, if it is greater than 0.5, then the second the element will accordingly increase by 1.

I modified the function so that it immediately returns the number of the interval into which the value will fall with this argument.

var hist_min = 0;
var hist_max = 2;
var hist_range = hist_max-hist_min;
var hist_cols = 30;

var f = function(x) {
    return Math.floor(((3 * Math.sin(2 * x) * Math.pow(Math.cos(x), 4) -hist_min) / hist_range) * 
    hist_cols);
}

In the above example, I have 30 intervals, the left border of the left most is 0, the right is 2.

Next, I measure the execution speed of 3 * 10 ^ 6 iterations of this function.

var iteratitions = 3000000;

var start_time = Date.now ();
for (var i = 0; i < iteratitions; i ++) {
    var need_col = f(Math.random())
}
console.log("Finished in", Date.now() - start_time + "ms")

it turns out pretty quickly, on my computer ~ 100-200ms

However, I need to somehow save these intervals, for example, into an array.

I do so

var start_time = Date.now();

for (var i = 0; i < iteratitions; i ++) {
    var need_col = f(Math.random())
    arr[need_col]++;
}

console.log ("Finished in", Date.now () - start_time + "ms")

However, this already takes much longer ~ 1300ms

At first, I thought it was because arr[need_col]++ took a very long time to complete, however, if I did this:

for (var i = 0; i < iteratitions; i ++) {
    var need_col = f(Math.random())
    var need_col2 = 3
    arr[need_col2]++;
}

And it already runs for ~ 130ms

The question is, why if I just save the value of the function f to the variable need_col, everything works quickly, and as soon as I use the variable need_col (I pass it as an index), everything slows down at times?

I bring all the code

var hist_min = 0;
var hist_max = 2;
var hist_range = hist_max-hist_min;
var hist_cols = 30;

var need_col = 0;

/*
var f = function(x) {
 return 3*Math.sin(2*x)*Math.pow(Math.cos(x), 4)
}
*/

var f = function(x) {
 return  Math.floor(((3*Math.sin(2*x)*Math.pow(Math.cos(x), 4)-hist_min)/hist_range) * hist_cols);
}

var iteratitions = 3000000;
var arr = [];

// инициализация
for (var i=0; i < hist_cols; i++) {
 arr.push(0)
}

// пустой цикл занимает время
var start_time = Date.now();

for (var i=0; i < iteratitions; i++) {
}
console.log("empty loop finished in",Date.now()-start_time+"ms")


// просто увеличение элемента массива по индексу
var start_time = Date.now();

for (var i=0; i < iteratitions; i++) {
 var need_col = 3
 arr[need_col]++;
}
console.log("arr[need_col]++; Finished in",Date.now()-start_time+"ms")


// просто выполение f(x) 
var start_time = Date.now();

for (var i=0; i < iteratitions; i++) {
 need_col = f(Math.random())
 //var need_col2 = 3
 //arr[need_col2]++;
}
console.log("just f(x) finished in",Date.now()-start_time+"ms")
//console.log(need_col)

// заполнение массива тем, что нам нужно
var start_time = Date.now();

for (var i=0; i < iteratitions; i++) {
 var need_col = f(Math.random())
 if (need_col > 0 && need_col < hist_cols) {
  arr[need_col]++;
 }
 
}
console.log("filling array f(x) finished in",Date.now()-start_time+"ms")

console.log("arr=", arr)

P.S. there are slightly different numbers on my computer (I execute the code through node)

my console output

  • Cannot reproduce. For me the snippet results in: empty loop finished in 18ms; arr[need_col]++; Finished in 19ms; just f(x) finished in 732ms; filling array f(x) finished in 692ms – Jonas Wilms May 14 '20 at 15:03
  • 1
    Yes, it's very strange, that in my local node machine just f(x) run so fast, i think that it's because node engine ingores `f(Math.random())`, so if i add after `console.log("just f(x) finished in",Date.now()-start_time+"ms")` command `console.log(need_col) ` it runs slow( – Данил Черкашин May 14 '20 at 15:07
  • Perhaps you need a [better mechanism](https://stackoverflow.com/a/1975103/238704) for timing code. – President James K. Polk May 14 '20 at 19:33

0 Answers0