2

My sample code to define and fill up then output an (Integer) IOArray:

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}

import Data.Array
import Data.Array.IO

for_ xs f =  mapM_ f xs

a_size = 10000 :: Int

main :: IO()
main = do 
      a <- newArray (0,a_size-1) 1 :: IO (IOArray Int Integer)
      for_ [3,4..(a_size-1)] $ \i -> do -- generate the a array
         t1 <- readArray a (i-3)
         t2 <- readArray a (i-2)
         t3 <- readArray a (i-1)
         writeArray a i (4*t1+t2+2*t3)
      for_ [0,1..(a_size-1)] $ \i -> do -- print the terms of array
         temp <- readArray a i
         print(temp)
      return()

Obviously my real code is longer to compute (another) 'a' Integer array. I would like to speedup the output section using bytestring, but don't know how to do it.

  • First of all, `import Control.Monad (forM_)`. Secondly, how do you know that outputting is what is taking a long time? Have you run a profiler? What if you collected all of the values to print and then printed them all at once? Do you need the array to contain `Integer` values or can you use `Int` or possibly an unboxed `Int`? – bheklilr Mar 10 '14 at 17:53
  • I'm pretty sure that the main bottleneck is just that it takes time to print that many characters to the screen, regardless of the string representation. You may consider writing to a file instead of the screen, particularly when you have this many values. You're more likely to get a higher write speed than to `stdout`, depending on your harddrive. Even still, 10000 values, most of which are hundreds of digits, will take up several megabytes, you'll have a noticeable write time no matter what. – bheklilr Mar 10 '14 at 18:36
  • The numbers are pretty big, so (not counting very few) will not fit in Int type. My experience shows that the input/output with bytestring is roughly 6-7 times faster, see the sample solution in haskell using bytestring: https://mukeshiiitm.wordpress.com/2011/05/31/spoj-31-fast-multiplication/ this gets AC, but with an easy approach (without bytestring) solves only the tutorial problem at http://www.spoj.com/problems/TMUL/ but is unable to get ac for http://www.spoj.com/problems/MUL/. But on that weblog the sample codes are different what I would like to see. – Szabo Balazs Mar 10 '14 at 19:29
  • 1
    Just figured out: BS.putStrLn ( BS.pack.show $ a ) this output a single integer, the bad news is that it gives the same poor performance what we can reach with only print on http://www.spoj.com/problems/TMUL/ . OK, this code is different from the long BS.interact $ BS.unlines . map ( solve . map readInteger . BS.words ) . tail . BS.lines But I really don't see why this is roughly 6 times faster than my shorter code (or print) what is also using ByteStrings. – Szabo Balazs Mar 11 '14 at 01:55

0 Answers0