Dot product and helper methods

In this section we look at dot product and helper methods. Now we can implement the dot product of two vectors using C++. All the code should be placed in the native-lib.cpp file. Starting from Armv8.4a, the dot product is part of the new instruction set. This corresponds to some Cortex-A75 designs and all Cortex-A76 designs onwards. Exploring the Arm dot product instructions includes for more information. Follow these steps:

  • Beginning with the helper method that generates the ramp, which is the vector of 16-bit integers incremented from the code startValue in the following example:

short* generateRamp(short startValue, short len) {
	short* ramp = new short[len];
	for(short i = 0; i < len; i++) {
    		ramp[i] = startValue + i;
	return ramp;
  • Implement the msElapsedTime and now methods, which are used later to determine the code execution time:
double msElapsedTime(chrono::system_clock::time_point start) {
	auto end = chrono::system_clock::now();
	return chrono::duration_cast<chrono::milliseconds>(end - start).count();

chrono::system_clock::time_point now() {
	return chrono::system_clock::now();

The msElapsedTime method calculates the amount of time, expressed in milliseconds, that has passed from a starting point. The now method is a handy wrapper for the std::chrono::system_clock::now method, which returns the current time.

  • Create the actual dot product method. To calculate a dot product of two equal-length vectors, multiply vectors element-by-element, then accumulate the resulting products. Here you can see a straightforward implementation of this algorithm:
int dotProduct(short* vector1, short* vector2, short len) {
	int result = 0;
	for(short i = 0; i < len; i++) {
    	    result += vector1[i] * vector2[i];
	return result;

The previous implementation uses a for loop. So we sequentially multiply vector elements and then accumulate the resulting products in a local variable called result.

Previous Next