-
-
Save voidlizard/88a1f42a06ea4dea9cf3 to your computer and use it in GitHub Desktop.
How do really Haskell suck? Really it doesn't
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- C | |
dmz@x201:~/prj/haskell/ffi$ cat ./calculateFCS.c | |
#include "calculateFCS.h" | |
#include <stdio.h> | |
unsigned short calculateFCS(unsigned short FCS, unsigned char b ) | |
{ | |
unsigned char i; | |
unsigned short w; | |
w = ( b ^ FCS ) & 0xFF; | |
i = 8; | |
do{ | |
if( w & 1 ) | |
{ | |
w >>= 1; | |
w ^= 0x8408; | |
} | |
else | |
{ | |
w >>= 1; | |
} | |
} while( --i ); | |
return ( w ^ ( FCS >> 8 ) ); | |
} | |
int main(int a, char **b) { | |
int i = 0; | |
int j = 10; | |
for(j=0; j<10; j++) { | |
unsigned short crc = 0xFFFF; | |
for( i = 0; i < 10000000; i++ ) { | |
crc = calculateFCS(crc, (unsigned char)(i+j)); | |
} | |
printf("%04X\n", crc); | |
} | |
} | |
dmz@x201:~/prj/haskell/ffi$ gcc -O2 ./calculateFCS.c | |
dmz@x201:~/prj/haskell/ffi$ time ./a.out | |
67B9 | |
4F71 | |
30AA | |
0652 | |
4814 | |
E76D | |
3C33 | |
D9CA | |
86D6 | |
71C8 | |
real 0m4.864s | |
user 0m4.850s | |
sys 0m0.000s | |
--- haskell | |
module Main where | |
import Data.Word | |
import Data.Bits | |
import Text.Printf | |
import Control.Monad | |
crc16 :: Word16 -> Word8 -> Word16 | |
crc16 fcs b = | |
let b' = fromIntegral b :: Word16 | |
w = (b' `xor` fcs) .&. 0xFF :: Word16 | |
w' = bit $! bit $! bit $! bit $! bit $! bit $! bit $! bit w | |
in w' `xor` ( fcs `shiftR` 8 ) | |
where bit x = let r = x `shiftR` 1 | |
in if ((x .&. 1) == 1) then r `xor` 0x8408 else r | |
{-# INLINE bit #-} | |
main = do | |
flip mapM_ [0..9] $ \i -> | |
do let wtf = foldl (\crc x -> crc16 crc (x+i)) 0xFFFF [fromIntegral b :: Word8 | b <- [0..10000000-1]] | |
printf "%04X\n" wtf | |
dmz@x201:~/prj/haskell/ffi$ ghc -O2 --make ./realWtf.hs | |
dmz@x201:~/prj/haskell/ffi$ time ./realWtf | |
67B9 | |
4F71 | |
30AA | |
0652 | |
4814 | |
E76D | |
3C33 | |
D9CA | |
86D6 | |
71C8 | |
real 0m6.508s | |
user 0m6.180s | |
sys 0m0.200s | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment