SlideShare a Scribd company logo
1 of 22
Download to read offline
Erlang / Elixir Meetup Zürich
Bare
Metal
Performance
Integration with non-BEAM code
Source: https://potatosalad.io/2017/08/05/latency-of-native-functions-for-erlang-and-elixir
Learn more at: http://erlang.org/doc/tutorial/introduction.html
JASON: An example of fast code on the VM
A JSON parsing library by Michał Muskała
Hex: https://hex.pm/packages/jason
Github: https://github.com/michalmuskala/jason
Protocol based, focused on speed rather than rich feature set
Pretty is not a concern; speed is.
JASON: An example of fast code on the VM
defp array(data, original, skip, stack, key_decode, string_decode, value) do
bytecase data do
_ in 'sntr', rest ->
array(rest, original, skip + 1, stack, key_decode, string_decode, value)
_ in ']', rest ->
[acc | stack] = stack
value = :lists.reverse(acc, [value])
continue(rest, original, skip + 1, stack, key_decode, string_decode, value)
_ in ',', rest ->
[acc | stack] = stack
value(rest, original, skip + 1, [@array, [value | acc] | stack], key_decode, string_decode)
_, _rest ->
error(original, skip)
-<_-:bits-> ->
empty_error(original, skip)
end
end
@compile {:inline, object: 6}
defp object(rest, original, skip, stack, key_decode, string_decode) do
key(rest, original, skip, [[] | stack], key_decode, string_decode)
end
Integration with non-BEAM code
Source: https://potatosalad.io/2017/08/05/latency-of-native-functions-for-erlang-and-elixir
Calling External Processes: Ports
Provide an easy way to start an external native process and connect stdin / stdout
●
Looks like a process from the BEAM code side
Easy-peasy:
port = Port.open({:spawn, cmd}, [:binary])
Port.command(port, msg)
Responses delivered using messages: just use a receive block!
{port, {:data, result}}
Various libraries on hex.pm that make ports even nicer to use
●
Some specifc to languages e.g. python, ruby
Natively compiled plugins: Port Drivers
Used for I/O outside of the BEAM
●
Historically, anyways: fle I/O is moving to BIFs (speeeeed!)
Requires writing a driver in C using the moderately complex port driver API
Run in-process
●
Good latency
●
Crashes bring down your VM
●
Still incurs the overhead of message passing
●
Serialization overhead for terms, but usually negligible in the bigger scheme
●
Follows the familiar OTP mechanism of processes, so nice for async use
Natively compiled plugins: Port Drivers
static ErlDrvEntry latency_driver_entry = {
latency_drv_init, -* F_PTR init, called at system startup for statically linked drivers, and after loading for
dynamically loaded drivers -/
latency_drv_start, -* F_PTR start, called when open_port/2 is invoked, return value -1 means failure -/
latency_drv_stop, -* F_PTR stop, called when port is closed, and when the emulator is halted -/
latency_drv_output, -* F_PTR output, called when we have output from Erlang to the port -/
NULL, -* F_PTR ready_input, called when we have input from one of the driver's handles -/
NULL, -* F_PTR ready_output, called when output is possible to one of the driver's handles -/
"latency_drv", -* char *driver_name, name supplied as command in erlang:open_port/2 -/
latency_drv_finish, -* F_PTR finish, called before unloading the driver - dynamic drivers only -/
NULL, -* void *handle, reserved, used by emulator internally -/
latency_drv_control, -* F_PTR control, "ioctl" for drivers - invoked by port_control/3 -/
NULL, -* F_PTR timeout, handling of time-out in driver -/
latency_drv_outputv, -* F_PTR outputv, called when we have output from Erlang to the port -/
NULL, -* F_PTR ready_async, only for async drivers -/
NULL, -* F_PTR flush, called when the port is about to be closed, and there is data in the driver
queue that must be flushed before 'stop' can be called -/
latency_drv_call, -* F_PTR call, works mostly like 'control', a synchronous call into the driver -/
NULL, -* F_PTR event, called when an event selected by driver_event() has occurred -/
ERL_DRV_EXTENDED_MARKER, -* int extended marker, should always be set to indicate driver versioning -/
ERL_DRV_EXTENDED_MAJOR_VERSION, -* int major_version, should always be set to this value -/
ERL_DRV_EXTENDED_MINOR_VERSION, -* int minor_version, should always be set to this value -/
LATENCY_DRV_FLAGS, -* int driver_flags, see documentation -/
NULL, -* void *handle2, reserved, used by emulator internally -/
NULL, -* F_PTR process_exit, called when a process monitor fires -/
NULL -* F_PTR stop_select, called to close an event object -/
};
Natively compiled plugins: Port Drivers
static ErlDrvSSizeT
latency_drv_call(ErlDrvData drv_data,
unsigned int command,
char *buf, ErlDrvSizeT len,
char -*rbuf,
ErlDrvSizeT rlen,
unsigned int *flags)
{
if (rlen < len) {
*rbuf = (void *)driver_alloc(len);
}
(void)memcpy(*rbuf, buf, len);
return (ErlDrvSSizeT)(len);
}
Native Instruction Functions: NIFs
Pathway for plugins and bindings for the BEAM
Simplest, fastest … least safe
Natively compiled, run in-process, have no process or other OTP integration
Newest of the mechanisms, and looks a lot like many language’s bindings mechanisms
Functions get an environment object and an argc/argv pair, return ERL_NIF_TERMs
static ERL_NIF_TERM
latency_nif_echo_1(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
return argv[0];
}
Native Instruction Functions: NIFs
Pathway for plugins and bindings for the BEAM
Simplest, fastest … least safe
Natively compiled, run in-process, have no process or other OTP integration
Newest of the mechanisms, and looks a lot like many language’s bindings mechanisms
Functions get an environment object and an argc/argv pair, return ERL_NIF_TERMs
static ERL_NIF_TERM
latency_nif_echo_1(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
return argv[0];
}
Native Instruction Functions: NIFs
Loaded with erlang:load_nif/2
Binds the calls in the library to erlang functions named the same:
echo(_Term) → erlang:nif_error({nif_not_loaded, ?MODULE}).
Then just call them as you would any any other function!
latency_nif:echo(-<”foo”->).
Yielding and Dirty NIFs
A NIF running in a normal BEAM scheduler thread that takes more than ~1ms causes chaos
These are called “dirty” NIFs, and there are now schedulers for them
●
CPU bound
●
I/O bound
Use the enif_schedule_nif function
●
ERL_NIF_DIRTY_JOB_CPU_BOUND / ERL_NIF_DIRTY_JOB_IO_BOUND
ERL_NIF_TERM enif_schedule_nif(ErlNifEnv* env, const char* fun_name, int flags,
ERL_NIF_TERM (*fp)(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]), int argc,
const ERL_NIF_TERM argv[])
Dirty NIFs
static ERL_NIF_TERM
latency_nif_dirty_cpu_echo_1(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
return enif_schedule_nif(env, "dirty_cpu_echo",
ERL_NIF_DIRTY_JOB_CPU_BOUND,
latency_nif_echo_1, argc, argv);
}
C++ NIFs with nifpp
Single-header library → https://github.com/goertzenator/nifpp
●
Overloaded get()/make() wrappers for the enif_get_xxx()/enif_make_xxx() C API.
●
get()/make() support for STL containers tuple, vector, array, list, deque, set, unordered_set,
multiset, map, and unordered_map.
●
get()/make() support for nested containers.
●
A resource pointer type so that any type can be easily used as a NIF resource. Think of it as a
std::shared_ptr that the emulator can hold references to.
C++ NIFs with nifpp
template<typename TK, typename TV>
nifpp-:TERM mapflip_test(ErlNifEnv* env, ERL_NIF_TERM term)
{
std-:map<TK,TV> inmap;
std-:map<TV,TK> outmap;
get_throws(env, term, inmap);
for (auto i = inmap.begin(); i -= inmap.end(); i-+)
{
outmap[i->second] = i->first;
}
return make(env, outmap);
}
Protecting the home base: Port + NIF?
What if you have a number of NIFs that you want to run in more complex BEAM code …
… and you don’t want to risk the stability of your VM?
SafeExecEnv to the rescue: starts an external BEAM VM linked to the spawning BEAM in
which you can run functions of arbitrary complexity … GenServers, message passing, whatever
SafeExecEnv
defmodule MyApp do
@moduledoc false
use Application
def start(_type, _args) do
children = [SafeExecEnv]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
End
SafeExecEnv.exec(fn → 2 * 3 end)
SafeExecEnv.exec(module, func, args)
# that’s it :)
SafeExecEnv
Available on Hex.pm at https://hex.pm/packages/safe_exec_env
Works with releases, unlike OTP’s slave module
Feature ideas:
●
Multiple external nodes?
●
Per-call nodes?
●
Async conveniences?
Bare metal performance in Elixir

More Related Content

What's hot

Zn task - defcon russia 20
Zn task  - defcon russia 20Zn task  - defcon russia 20
Zn task - defcon russia 20DefconRussia
 
How Functions Work
How Functions WorkHow Functions Work
How Functions WorkSaumil Shah
 
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack FirmwareSimen Li
 
Unit 1
Unit 1Unit 1
Unit 1siddr
 
ARM Trusted FirmwareのBL31を単体で使う!
ARM Trusted FirmwareのBL31を単体で使う!ARM Trusted FirmwareのBL31を単体で使う!
ARM Trusted FirmwareのBL31を単体で使う!Mr. Vengineer
 
Specializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network StackSpecializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network StackKernel TLV
 
Implementation of the ZigBee ZCL Reporting Configuration Features
Implementation of the ZigBee ZCL Reporting Configuration FeaturesImplementation of the ZigBee ZCL Reporting Configuration Features
Implementation of the ZigBee ZCL Reporting Configuration FeaturesSimen Li
 
No instrumentation Golang Logging with eBPF (GoSF talk 11/11/20)
No instrumentation Golang Logging with eBPF (GoSF talk 11/11/20)No instrumentation Golang Logging with eBPF (GoSF talk 11/11/20)
No instrumentation Golang Logging with eBPF (GoSF talk 11/11/20)Pixie Labs
 
Troubleshooting Linux Kernel Modules And Device Drivers
Troubleshooting Linux Kernel Modules And Device DriversTroubleshooting Linux Kernel Modules And Device Drivers
Troubleshooting Linux Kernel Modules And Device DriversSatpal Parmar
 
Exploit techniques - a quick review
Exploit techniques - a quick reviewExploit techniques - a quick review
Exploit techniques - a quick reviewCe.Se.N.A. Security
 
Implementing Lightweight Networking
Implementing Lightweight NetworkingImplementing Lightweight Networking
Implementing Lightweight Networkingguest6972eaf
 
Exception handling in Pipelining in COA
Exception handling in Pipelining in COAException handling in Pipelining in COA
Exception handling in Pipelining in COARishavChandel1
 
Course lecture - An introduction to the Return Oriented Programming
Course lecture - An introduction to the Return Oriented ProgrammingCourse lecture - An introduction to the Return Oriented Programming
Course lecture - An introduction to the Return Oriented ProgrammingJonathan Salwan
 
An introduction to ROP
An introduction to ROPAn introduction to ROP
An introduction to ROPSaumil Shah
 
PHP 7 OPCache extension review
PHP 7 OPCache extension reviewPHP 7 OPCache extension review
PHP 7 OPCache extension reviewjulien pauli
 

What's hot (20)

Zn task - defcon russia 20
Zn task  - defcon russia 20Zn task  - defcon russia 20
Zn task - defcon russia 20
 
Return Oriented Programming (ROP) Based Exploits - Part I
Return Oriented Programming  (ROP) Based Exploits  - Part IReturn Oriented Programming  (ROP) Based Exploits  - Part I
Return Oriented Programming (ROP) Based Exploits - Part I
 
How Functions Work
How Functions WorkHow Functions Work
How Functions Work
 
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
 
Linux interrupts
Linux interruptsLinux interrupts
Linux interrupts
 
Unit 1
Unit 1Unit 1
Unit 1
 
ARM Trusted FirmwareのBL31を単体で使う!
ARM Trusted FirmwareのBL31を単体で使う!ARM Trusted FirmwareのBL31を単体で使う!
ARM Trusted FirmwareのBL31を単体で使う!
 
Specializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network StackSpecializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network Stack
 
Implementation of the ZigBee ZCL Reporting Configuration Features
Implementation of the ZigBee ZCL Reporting Configuration FeaturesImplementation of the ZigBee ZCL Reporting Configuration Features
Implementation of the ZigBee ZCL Reporting Configuration Features
 
Linux : PSCI
Linux : PSCILinux : PSCI
Linux : PSCI
 
No instrumentation Golang Logging with eBPF (GoSF talk 11/11/20)
No instrumentation Golang Logging with eBPF (GoSF talk 11/11/20)No instrumentation Golang Logging with eBPF (GoSF talk 11/11/20)
No instrumentation Golang Logging with eBPF (GoSF talk 11/11/20)
 
Troubleshooting Linux Kernel Modules And Device Drivers
Troubleshooting Linux Kernel Modules And Device DriversTroubleshooting Linux Kernel Modules And Device Drivers
Troubleshooting Linux Kernel Modules And Device Drivers
 
Advance ROP Attacks
Advance ROP AttacksAdvance ROP Attacks
Advance ROP Attacks
 
Exploit techniques - a quick review
Exploit techniques - a quick reviewExploit techniques - a quick review
Exploit techniques - a quick review
 
Implementing Lightweight Networking
Implementing Lightweight NetworkingImplementing Lightweight Networking
Implementing Lightweight Networking
 
Exception handling in Pipelining in COA
Exception handling in Pipelining in COAException handling in Pipelining in COA
Exception handling in Pipelining in COA
 
Php engine
Php enginePhp engine
Php engine
 
Course lecture - An introduction to the Return Oriented Programming
Course lecture - An introduction to the Return Oriented ProgrammingCourse lecture - An introduction to the Return Oriented Programming
Course lecture - An introduction to the Return Oriented Programming
 
An introduction to ROP
An introduction to ROPAn introduction to ROP
An introduction to ROP
 
PHP 7 OPCache extension review
PHP 7 OPCache extension reviewPHP 7 OPCache extension review
PHP 7 OPCache extension review
 

Similar to Bare metal performance in Elixir

proxyc CSAPP Web proxy NAME IMPORTANT Giv.pdf
  proxyc  CSAPP Web proxy   NAME    IMPORTANT Giv.pdf  proxyc  CSAPP Web proxy   NAME    IMPORTANT Giv.pdf
proxyc CSAPP Web proxy NAME IMPORTANT Giv.pdfajay1317
 
Pragmatic Optimization in Modern Programming - Demystifying the Compiler
Pragmatic Optimization in Modern Programming - Demystifying the CompilerPragmatic Optimization in Modern Programming - Demystifying the Compiler
Pragmatic Optimization in Modern Programming - Demystifying the CompilerMarina Kolpakova
 
#include avrinterrupt.h The global interrupt flag is maintained.pdf
#include avrinterrupt.h The global interrupt flag is maintained.pdf#include avrinterrupt.h The global interrupt flag is maintained.pdf
#include avrinterrupt.h The global interrupt flag is maintained.pdfarasanlethers
 
httplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docxhttplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docxadampcarr67227
 
Epoll - from the kernel side
Epoll -  from the kernel sideEpoll -  from the kernel side
Epoll - from the kernel sidellj098
 
PHP Internals and Virtual Machine
PHP Internals and Virtual MachinePHP Internals and Virtual Machine
PHP Internals and Virtual Machinejulien pauli
 
Unit 4
Unit 4Unit 4
Unit 4siddr
 
Reversing malware analysis training part4 assembly programming basics
Reversing malware analysis training part4 assembly programming basicsReversing malware analysis training part4 assembly programming basics
Reversing malware analysis training part4 assembly programming basicsCysinfo Cyber Security Community
 
Regular Expression (RegExp)
Regular Expression (RegExp)Regular Expression (RegExp)
Regular Expression (RegExp)Davide Dell'Erba
 
망고100 보드로 놀아보자 15
망고100 보드로 놀아보자 15망고100 보드로 놀아보자 15
망고100 보드로 놀아보자 15종인 전
 
Building apache modules
Building apache modulesBuilding apache modules
Building apache modulesMarian Marinov
 
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Vincenzo Iozzo
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from insidejulien pauli
 
Msfpayload/Msfencoder cheatsheet
Msfpayload/Msfencoder cheatsheetMsfpayload/Msfencoder cheatsheet
Msfpayload/Msfencoder cheatsheetCe.Se.N.A. Security
 
Php opcodes sep2008
Php opcodes sep2008Php opcodes sep2008
Php opcodes sep2008bengiuliano
 
Virtual platform
Virtual platformVirtual platform
Virtual platformsean chen
 
Create your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaCreate your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaPatrick Allaert
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisFastly
 
Alexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for DevelopersAlexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for DevelopersDevDay Dresden
 

Similar to Bare metal performance in Elixir (20)

proxyc CSAPP Web proxy NAME IMPORTANT Giv.pdf
  proxyc  CSAPP Web proxy   NAME    IMPORTANT Giv.pdf  proxyc  CSAPP Web proxy   NAME    IMPORTANT Giv.pdf
proxyc CSAPP Web proxy NAME IMPORTANT Giv.pdf
 
Pragmatic Optimization in Modern Programming - Demystifying the Compiler
Pragmatic Optimization in Modern Programming - Demystifying the CompilerPragmatic Optimization in Modern Programming - Demystifying the Compiler
Pragmatic Optimization in Modern Programming - Demystifying the Compiler
 
#include avrinterrupt.h The global interrupt flag is maintained.pdf
#include avrinterrupt.h The global interrupt flag is maintained.pdf#include avrinterrupt.h The global interrupt flag is maintained.pdf
#include avrinterrupt.h The global interrupt flag is maintained.pdf
 
httplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docxhttplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docx
 
Epoll - from the kernel side
Epoll -  from the kernel sideEpoll -  from the kernel side
Epoll - from the kernel side
 
PHP Internals and Virtual Machine
PHP Internals and Virtual MachinePHP Internals and Virtual Machine
PHP Internals and Virtual Machine
 
Unit 4
Unit 4Unit 4
Unit 4
 
Reversing malware analysis training part4 assembly programming basics
Reversing malware analysis training part4 assembly programming basicsReversing malware analysis training part4 assembly programming basics
Reversing malware analysis training part4 assembly programming basics
 
Regular Expression (RegExp)
Regular Expression (RegExp)Regular Expression (RegExp)
Regular Expression (RegExp)
 
망고100 보드로 놀아보자 15
망고100 보드로 놀아보자 15망고100 보드로 놀아보자 15
망고100 보드로 놀아보자 15
 
Building apache modules
Building apache modulesBuilding apache modules
Building apache modules
 
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from inside
 
Msfpayload/Msfencoder cheatsheet
Msfpayload/Msfencoder cheatsheetMsfpayload/Msfencoder cheatsheet
Msfpayload/Msfencoder cheatsheet
 
Php opcodes sep2008
Php opcodes sep2008Php opcodes sep2008
Php opcodes sep2008
 
Virtual platform
Virtual platformVirtual platform
Virtual platform
 
Create your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaCreate your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 Verona
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
 
freertos-proj.pdf
freertos-proj.pdffreertos-proj.pdf
freertos-proj.pdf
 
Alexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for DevelopersAlexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for Developers
 

Recently uploaded

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 

Recently uploaded (20)

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 

Bare metal performance in Elixir

  • 1. Erlang / Elixir Meetup Zürich
  • 2.
  • 4. Integration with non-BEAM code Source: https://potatosalad.io/2017/08/05/latency-of-native-functions-for-erlang-and-elixir Learn more at: http://erlang.org/doc/tutorial/introduction.html
  • 5. JASON: An example of fast code on the VM A JSON parsing library by Michał Muskała Hex: https://hex.pm/packages/jason Github: https://github.com/michalmuskala/jason Protocol based, focused on speed rather than rich feature set Pretty is not a concern; speed is.
  • 6. JASON: An example of fast code on the VM defp array(data, original, skip, stack, key_decode, string_decode, value) do bytecase data do _ in 'sntr', rest -> array(rest, original, skip + 1, stack, key_decode, string_decode, value) _ in ']', rest -> [acc | stack] = stack value = :lists.reverse(acc, [value]) continue(rest, original, skip + 1, stack, key_decode, string_decode, value) _ in ',', rest -> [acc | stack] = stack value(rest, original, skip + 1, [@array, [value | acc] | stack], key_decode, string_decode) _, _rest -> error(original, skip) -<_-:bits-> -> empty_error(original, skip) end end @compile {:inline, object: 6} defp object(rest, original, skip, stack, key_decode, string_decode) do key(rest, original, skip, [[] | stack], key_decode, string_decode) end
  • 7. Integration with non-BEAM code Source: https://potatosalad.io/2017/08/05/latency-of-native-functions-for-erlang-and-elixir
  • 8. Calling External Processes: Ports Provide an easy way to start an external native process and connect stdin / stdout ● Looks like a process from the BEAM code side Easy-peasy: port = Port.open({:spawn, cmd}, [:binary]) Port.command(port, msg) Responses delivered using messages: just use a receive block! {port, {:data, result}} Various libraries on hex.pm that make ports even nicer to use ● Some specifc to languages e.g. python, ruby
  • 9. Natively compiled plugins: Port Drivers Used for I/O outside of the BEAM ● Historically, anyways: fle I/O is moving to BIFs (speeeeed!) Requires writing a driver in C using the moderately complex port driver API Run in-process ● Good latency ● Crashes bring down your VM ● Still incurs the overhead of message passing ● Serialization overhead for terms, but usually negligible in the bigger scheme ● Follows the familiar OTP mechanism of processes, so nice for async use
  • 10. Natively compiled plugins: Port Drivers static ErlDrvEntry latency_driver_entry = { latency_drv_init, -* F_PTR init, called at system startup for statically linked drivers, and after loading for dynamically loaded drivers -/ latency_drv_start, -* F_PTR start, called when open_port/2 is invoked, return value -1 means failure -/ latency_drv_stop, -* F_PTR stop, called when port is closed, and when the emulator is halted -/ latency_drv_output, -* F_PTR output, called when we have output from Erlang to the port -/ NULL, -* F_PTR ready_input, called when we have input from one of the driver's handles -/ NULL, -* F_PTR ready_output, called when output is possible to one of the driver's handles -/ "latency_drv", -* char *driver_name, name supplied as command in erlang:open_port/2 -/ latency_drv_finish, -* F_PTR finish, called before unloading the driver - dynamic drivers only -/ NULL, -* void *handle, reserved, used by emulator internally -/ latency_drv_control, -* F_PTR control, "ioctl" for drivers - invoked by port_control/3 -/ NULL, -* F_PTR timeout, handling of time-out in driver -/ latency_drv_outputv, -* F_PTR outputv, called when we have output from Erlang to the port -/ NULL, -* F_PTR ready_async, only for async drivers -/ NULL, -* F_PTR flush, called when the port is about to be closed, and there is data in the driver queue that must be flushed before 'stop' can be called -/ latency_drv_call, -* F_PTR call, works mostly like 'control', a synchronous call into the driver -/ NULL, -* F_PTR event, called when an event selected by driver_event() has occurred -/ ERL_DRV_EXTENDED_MARKER, -* int extended marker, should always be set to indicate driver versioning -/ ERL_DRV_EXTENDED_MAJOR_VERSION, -* int major_version, should always be set to this value -/ ERL_DRV_EXTENDED_MINOR_VERSION, -* int minor_version, should always be set to this value -/ LATENCY_DRV_FLAGS, -* int driver_flags, see documentation -/ NULL, -* void *handle2, reserved, used by emulator internally -/ NULL, -* F_PTR process_exit, called when a process monitor fires -/ NULL -* F_PTR stop_select, called to close an event object -/ };
  • 11. Natively compiled plugins: Port Drivers static ErlDrvSSizeT latency_drv_call(ErlDrvData drv_data, unsigned int command, char *buf, ErlDrvSizeT len, char -*rbuf, ErlDrvSizeT rlen, unsigned int *flags) { if (rlen < len) { *rbuf = (void *)driver_alloc(len); } (void)memcpy(*rbuf, buf, len); return (ErlDrvSSizeT)(len); }
  • 12. Native Instruction Functions: NIFs Pathway for plugins and bindings for the BEAM Simplest, fastest … least safe Natively compiled, run in-process, have no process or other OTP integration Newest of the mechanisms, and looks a lot like many language’s bindings mechanisms Functions get an environment object and an argc/argv pair, return ERL_NIF_TERMs static ERL_NIF_TERM latency_nif_echo_1(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { return argv[0]; }
  • 13. Native Instruction Functions: NIFs Pathway for plugins and bindings for the BEAM Simplest, fastest … least safe Natively compiled, run in-process, have no process or other OTP integration Newest of the mechanisms, and looks a lot like many language’s bindings mechanisms Functions get an environment object and an argc/argv pair, return ERL_NIF_TERMs static ERL_NIF_TERM latency_nif_echo_1(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { return argv[0]; }
  • 14. Native Instruction Functions: NIFs Loaded with erlang:load_nif/2 Binds the calls in the library to erlang functions named the same: echo(_Term) → erlang:nif_error({nif_not_loaded, ?MODULE}). Then just call them as you would any any other function! latency_nif:echo(-<”foo”->).
  • 15. Yielding and Dirty NIFs A NIF running in a normal BEAM scheduler thread that takes more than ~1ms causes chaos These are called “dirty” NIFs, and there are now schedulers for them ● CPU bound ● I/O bound Use the enif_schedule_nif function ● ERL_NIF_DIRTY_JOB_CPU_BOUND / ERL_NIF_DIRTY_JOB_IO_BOUND ERL_NIF_TERM enif_schedule_nif(ErlNifEnv* env, const char* fun_name, int flags, ERL_NIF_TERM (*fp)(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]), int argc, const ERL_NIF_TERM argv[])
  • 16. Dirty NIFs static ERL_NIF_TERM latency_nif_dirty_cpu_echo_1(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { return enif_schedule_nif(env, "dirty_cpu_echo", ERL_NIF_DIRTY_JOB_CPU_BOUND, latency_nif_echo_1, argc, argv); }
  • 17. C++ NIFs with nifpp Single-header library → https://github.com/goertzenator/nifpp ● Overloaded get()/make() wrappers for the enif_get_xxx()/enif_make_xxx() C API. ● get()/make() support for STL containers tuple, vector, array, list, deque, set, unordered_set, multiset, map, and unordered_map. ● get()/make() support for nested containers. ● A resource pointer type so that any type can be easily used as a NIF resource. Think of it as a std::shared_ptr that the emulator can hold references to.
  • 18. C++ NIFs with nifpp template<typename TK, typename TV> nifpp-:TERM mapflip_test(ErlNifEnv* env, ERL_NIF_TERM term) { std-:map<TK,TV> inmap; std-:map<TV,TK> outmap; get_throws(env, term, inmap); for (auto i = inmap.begin(); i -= inmap.end(); i-+) { outmap[i->second] = i->first; } return make(env, outmap); }
  • 19. Protecting the home base: Port + NIF? What if you have a number of NIFs that you want to run in more complex BEAM code … … and you don’t want to risk the stability of your VM? SafeExecEnv to the rescue: starts an external BEAM VM linked to the spawning BEAM in which you can run functions of arbitrary complexity … GenServers, message passing, whatever
  • 20. SafeExecEnv defmodule MyApp do @moduledoc false use Application def start(_type, _args) do children = [SafeExecEnv] opts = [strategy: :one_for_one, name: MyApp.Supervisor] Supervisor.start_link(children, opts) end End SafeExecEnv.exec(fn → 2 * 3 end) SafeExecEnv.exec(module, func, args) # that’s it :)
  • 21. SafeExecEnv Available on Hex.pm at https://hex.pm/packages/safe_exec_env Works with releases, unlike OTP’s slave module Feature ideas: ● Multiple external nodes? ● Per-call nodes? ● Async conveniences?