time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

main.js (2109B)


      1 /**
      2 * @license Apache-2.0
      3 *
      4 * Copyright (c) 2020 The Stdlib Authors.
      5 *
      6 * Licensed under the Apache License, Version 2.0 (the "License");
      7 * you may not use this file except in compliance with the License.
      8 * You may obtain a copy of the License at
      9 *
     10 *    http://www.apache.org/licenses/LICENSE-2.0
     11 *
     12 * Unless required by applicable law or agreed to in writing, software
     13 * distributed under the License is distributed on an "AS IS" BASIS,
     14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     15 * See the License for the specific language governing permissions and
     16 * limitations under the License.
     17 */
     18 
     19 'use strict';
     20 
     21 // VARIABLES //
     22 
     23 var M = 5;
     24 
     25 
     26 // MAIN //
     27 
     28 /**
     29 * Computes the dot product of `x` and `y`.
     30 *
     31 * @param {PositiveInteger} N - number of values over which to compute the dot product
     32 * @param {NumericArray} x - first input array
     33 * @param {integer} strideX - `x` stride length
     34 * @param {NumericArray} y - second input array
     35 * @param {integer} strideY - `y` stride length
     36 * @returns {number} dot product of `x` and `y`
     37 *
     38 * @example
     39 * var x = [ 4.0, 2.0, -3.0, 5.0, -1.0 ];
     40 * var y = [ 2.0, 6.0, -1.0, -4.0, 8.0 ];
     41 
     42 * var z = gdot( x.length, x, 1, y, 1 );
     43 * // returns -5.0
     44 */
     45 function gdot( N, x, strideX, y, strideY ) {
     46 	var dot;
     47 	var ix;
     48 	var iy;
     49 	var m;
     50 	var i;
     51 
     52 	dot = 0.0;
     53 	if ( N <= 0 ) {
     54 		return dot;
     55 	}
     56 	// Use unrolled loops if both strides are equal to `1`...
     57 	if ( strideX === 1 && strideY === 1 ) {
     58 		m = N % M;
     59 
     60 		// If we have a remainder, run a clean-up loop...
     61 		if ( m > 0 ) {
     62 			for ( i = 0; i < m; i++ ) {
     63 				dot += x[ i ] * y[ i ];
     64 			}
     65 		}
     66 		if ( N < M ) {
     67 			return dot;
     68 		}
     69 		for ( i = m; i < N; i += M ) {
     70 			dot += ( x[i]*y[i] ) + ( x[i+1]*y[i+1] ) + ( x[i+2]*y[i+2] ) + ( x[i+3]*y[i+3] ) + ( x[i+4]*y[i+4] ); // eslint-disable-line max-len
     71 		}
     72 		return dot;
     73 	}
     74 	if ( strideX < 0 ) {
     75 		ix = ( 1-N ) * strideX;
     76 	} else {
     77 		ix = 0;
     78 	}
     79 	if ( strideY < 0 ) {
     80 		iy = ( 1-N ) * strideY;
     81 	} else {
     82 		iy = 0;
     83 	}
     84 	for ( i = 0; i < N; i++ ) {
     85 		dot += ( x[ ix ] * y[ iy ] );
     86 		ix += strideX;
     87 		iy += strideY;
     88 	}
     89 	return dot;
     90 }
     91 
     92 
     93 // EXPORTS //
     94 
     95 module.exports = gdot;