Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembling a function as needed and computing it fast

There are interpreted languages out there, such as Lisp, Tcl, Perl, etc., that make it easy to define a lambda/proc/sub within your code during runtime and to evaluate it within the same session.

There are compiled languages out there, such as C++, that would execute much faster than the interpreted ones, yet defining a function within a compiled program during runtime and executing it is not easy, if at all possible.

The problem here is to do the following:

  1. Define a function during runtime: for example, based on the initial input data derive an analytic model of the data.

  2. Execute the above function fast in a loop: for example, apply the derived analytic model for analysing incoming data.

One solution that I saw was not very pretty:

  1. A procedure representing the analytic model was derived in embedded Tcl based on the initial input data.

  2. A lookup table was created by evaluating the procedure in Tcl on an array of sample points that, optimistically speaking, would cover the applicability range.

  3. The lookup table was passed from the Tcl interpreter back to the binary (which was developed in C++).

  4. Then the incoming data was analysed by interpolating between "close enough" values in the lookup table.

The above solution works, but has quite a few problems, both conceptual and computational. Thus the question: is it possible to define a function purely within C++ and make it available for execution within the same runtime session?

Conceptually speaking, is it possible to do something like create a function as a string, compile it in-memory, and somehow link it back into the binary that's being executed?

like image 914
Michael Avatar asked Sep 04 '13 17:09

Michael


1 Answers

If you want something working right out of the box have a look at ExprTK. If you want to write an expression parser yourself check out Boost Spirit.

An alternative would be to create C++ code on the fly, compile it as a shared library (plugin) and load it at runtime. This would probably be the fastest solution.

like image 172
ToniBig Avatar answered Oct 13 '22 00:10

ToniBig