Running built-in octave function in c++ code (using API) is taking longer time than running that function in Octave... Why so...?

Viewed 111

This is my C++ code (using C++ Octave API), which uses built-in Octave function filter(), which takes at least 3 arguments as input.

#include <iostream>
#include <complex>
#include "/usr/include/octave-4.2.2/octave/builtin-defun-decls.h"

int main (void) {
    int len = 10000000; // 10 millions
    Array<float> filter_taps(dim_vector (1,102),5.55); // # taps = 102
    Array<std::complex<float>> A(dim_vector (1,len), std::complex<float>(0x00,0x00));

    for (octave_idx_type i = 0; i < len; i++)
        A(0,i) = std::complex<float>(1,5);
    
    octave_value_list in;
    in.append(octave_value(filter_taps));
    in.append(octave_value(1));
    in.append(octave_value(A));

    octave_value_list out = Ffilter (in, 1);

    A = out(0).complex_array_value();
    return 0;
}

I am using Ubuntu 18.04 and Octave is installed in my system, and I am using Octave C++ API.

I compile this code by running g++ Ffilter.cpp -o Ffilter -loctave -loctinterp, and execute this by ./Ffilter. I am getting no error, results are exactly same as Octave output. But the execution time is approximately 9 seconds.

But when I run the equivalent code in Octave, then the execution time is 2.85 seconds. The snippet of Octave code is given below.

h = 5.55*ones(1,102);
A = ones(1,10000000)+i*5*ones(1,10000000);
A = filter(h,1,A);

As Octave functions itself written in C/C++, and also C++ is faster than Octave. Thus the execution time of the C++ code should be much shorter than Octave code but the opposite is happening...

  1. Why is this happening? What am I doing wrong?

  2. Is there any way to reduce the execution time to use the filter function (built-in) using C++ (Octave API)? If so, please provide a demo code.

1 Answers

You seem to be missing the big -O:

g++ ofilter.cpp -O3 -o Ffilter -loctave -loctinterp

Most optimizations are completely disabled at -O0 or if an -O level is not set on the command line, even if individual optimization flags are specified. 1

For me, however, the unoptimized version ran about as fast as octave. And octave wasn't that much slower than pure optimized C++. Maybe you should test it on different machine.

The octave is only slow when it is interpreting its own code. In the script you've posted there isn't much work for interpreter/virtual machine, it basically only does some moving of data around the ram and calls the same long running C++ functions as the compiled version.

Have a look at profile function, if you use it you'll see that time octave spends running the filter is about the same as the compiled version runtime. And C++ is faster in this case only because data initialization code is easier in the complied version.

Related