
So I have code like:
{-# NOINLINE count #-} count :: IORef Int count = unsafePerformIO $ newIORef 0
{-# NOINLINE getCount #-} getCount :: (Int -> a) -> a getCount f = let nextCount = (unsafePerformIO $ do oldCount <- readIORef count let newCount = oldCount + 1 writeIORef count newCount return oldCount) in seq nextCount (f nextCount)
It seems to work okay.
However, if you have any suggestions about how to make a FAST global counter I would be very glad to hear it. From profiling it seems like this code is a little expensive (also it is called quite frequently).
You could try the FastMutInt module from GHC (ghc/compiler/utils/FastMutInt.hs) to speed things up. Unfortunately unsafePerformIO has some unavoidable overhead: it can't be inlined because we don't want the compiler to see its definition. Cheers, Simon