How to find the number of cores at runtime in Haskell

前端 未结 5 1648
野趣味
野趣味 2021-02-13 06:22

Does Haskell have a method for determining the number of CPU cores present on a machine at runtime?

5条回答
  •  盖世英雄少女心
    2021-02-13 06:29

    Since version 6.12, GHC RTS includes a function getNumberOfProcessors, which is used to implement +RTS -N. You can access it in much the same manner as ordinary foreign functions. Warning: GHC-only and only works if the program was built with -threaded:

    {-# LANGUAGE ForeignFunctionInterface #-}
    import Foreign.C.Types (CInt)
    
    foreign import ccall "getNumberOfProcessors" c_getNumberOfProcessors :: IO CInt
    
    main :: IO ()
    main = c_getNumberOfProcessors >>= print
    

    Testing:

    $ ghc --make -threaded Main.hs
    [1 of 1] Compiling Main             ( Main.hs, Main.o )
    Linking Main ...
    $ ./Main                      
    1
    

提交回复
热议问题