performance - Simple math and saving to file takes too much time, compared to other languages -


recently me , friends benchmarking different programming languages. i'm learning haskell lately, wanted show functional language perform c simpler code. code pasted below, compiled ghc's -o3 option, executing 1.6 s on machine. equivalent scripts in python , ruby executed faster (it simple loop).

import system.io  saveline fh x = hputstrln fh $ show x ++ "\t" ++ show (x^2)  main =     fh <- openfile "haskell.txt" writemode     mapm (saveline fh) [1..999999]     hclose fh 

you can check out codes in other languages here (i wrote ones in python , ruby).

the question - how make run faster?

first, should avoid using -o3, because break code ( in gcc ). stick -o2.


second, haskell strings really slow.

but, there faster alternatives - , me, easiest 1 use data.bytestring ( little , old tutorial ).


third, if don't need maybe results mapm use mapm_ - it's much faster!


finally, here version of code, using data.bytestring:

{-# language overloadedstrings #-} --  line use "\t" instead of t.pack "\t"  import system.io import qualified data.bytestring.char8 t  helperfun x = t.concat [y, "\t", z]                       y = t.pack $ show x             z = t.pack $ show $ x^2  saveline fh x = t.hputstrln fh $ helperfun x  main =     fh <- openfile "haskell.txt" writemode     mapm_ (saveline fh) [1..999999]     hclose fh 

edit: user5402 said in comments it's not "much faster" strings version.

you should keep in mind code still using strings, , had additional overhead ( packing strings bytestring ) concat , hputstrln used bytestring.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -