Fastlog2 routine

J

Jacques Oberto

Hello All,

I am in the need of a fast log2 C# routine. Does anyone
have one handy ?
Alternatively, could anybody help translating the
following Delphi routine to C#?
Thanks,
Jacques

---------------
function fastlog2(val:single):single;
var
logg2,x:longint;
begin
x:=longint((@val)^);
logg2:=((x shr 23) and 255)-128;
x:=x and (not(255 shl 23));
x:=x+127 shl 23;
result:=single((@x)^)+logg2;
end;
---------------
 
P

Peter Duniho

Hello All,

I am in the need of a fast log2 C# routine. Does anyone
have one handy ?
Alternatively, could anybody help translating the
following Delphi routine to C#?

First, you should make sure you really need this. Many people find that
things that they think would be a bottleneck actually turn out not to be.
You should use the built-in Math methods, measuring performance and
determining for sure that your log calculation is in fact where you need
to reduce overhead. There's a pretty good chance it's not.

If after doing that, you are sure reimplementing it using the
approximation method will be helpful in improving throughput in your
application, you can convert the method you've posted by noting the
following equivalencies in C# for Delphi syntax:

Delphi C#
----------- -------
@foo &foo
foo^ *foo
bar(foo) (bar)foo
foo shr bar foo >> bar
foo and bar foo & bar
not foo ~foo
foo shl bar foo << bar

Note that to implement this in C#, you'll have to mark the code as
"unsafe", so that you can use pointers.

Pete
 
J

Jacques Oberto

"Peter Duniho" a écrit
First, you should make sure you really need this. Many people find that
things that they think would be a bottleneck actually turn out not to be.
You should use the built-in Math methods, measuring performance and
determining for sure that your log calculation is in fact where you need
to reduce overhead. There's a pretty good chance it's not.

If after doing that, you are sure reimplementing it using the
approximation method will be helpful in improving throughput in your
application, you can convert the method you've posted by noting the
following equivalencies in C# for Delphi syntax:

Pete

Hi Peter,

Delphi Fastlog2 is ~5x faster than the built-in log2 function. Similar
numbers have been described for the equivalent C++ routine. In my
specific case, FastLog2 is called four times per loop and the loop
is iterated between 2x10e6 and 10e7 times. The whole process
is over 3x faster with Fastlog2. It makes a huge difference.
I will use the Delphi-C# lexicon you gave me to check if I can get
a similar gain with the application ported to C#.
Many thanks,

Jacques
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top