herumi / mcl-wasm

59 stars 18 forks source link

emscripten optimisations #40

Closed atomictag closed 1 month ago

atomictag commented 1 month ago

Hi there, it's me again :)

I was trying out a few emcc options and added the following:

EMCC_OPT+= -flto 

then ran some benchmarks (BLS12-381, emcc 3.1.66):

MCL invVecInPlace (Fr, 1000 elements)
before: 0.31ms
after: 0.31ms 
==> no improvement on Fr math it seems

MCL invVecInPlace (Fp, 1000 elements)
before: 0.72ms
after: 0.44ms 
==> 39% improvement

MCL mulVec (MSM G1, 256 elements):
before:  30.22ms
after: 16.45ms
==> 45% improvement (note the fastest BLS MSM WASM I've ever used scored 13.5ms)

MCL pairing (averaged over 1000 random pairings):
before: 3.58ms
after: 2.86ms
==> 25% improvement

In my tests it appears that -flto produces significant improvements on math ops in G1/G2 (and possibly GT).

I ran this modified library over 600 complex tests on various algorithms and real-life applications that I have accumulated and encountered no issue. However my focus is solely on BLS12.381 in "Eth mode" so I can't speak for other curves/settings.

But it looks promising!

Other options I have tried

EMCC_OPT+=-O3 -DNDEBUG -std=c++11 # compiles fine, no measurable effects
EMCC_OPT+=-ffast-math # no measurable effects, might be unsafe
EMCC_OPT+= -s FILESYSTEM=0 -s ASSERTIONS=0 # this would make sense to reduce code size (maybe?)

What do you think? 🙏

herumi commented 1 month ago

Thank you for your interesing report. I've tried those options.

The size of mcl_c.js is reduced from 660097 bytes to 622165 bytes with -flto.

function/usec no -flto -flto
pairing 2412.492 2086.236
millerLoop 1006.681 917.331
finalExp 1334.797 1250.731
precomputedMillerLoop 735.137 741.364
G1::add 3.084 2.855
G1::dbl 2.285 2.015
G1::mul 279.962 203.932
G2::add 7.657 6.774
G2::dbl 3.462 3.243
G2::mul 459.43 405.152

-ffast-math may improve floating point operations but mcl does not use them. -s FILESYSTEM=0 -s ASSERTIONS=0 did not change the binary. So I will append -flto option.

atomictag commented 1 month ago

awesome - and thank you for the new release