How to find the number of cores at runtime in Haskell

前端 未结 5 877
终归单人心
终归单人心 2021-02-13 06:16

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

相关标签:
5条回答
  • 2021-02-13 06:28

    Since base 4.5 you can use getNumProcessors from GHC.Conc. This is good since the number of capabilities can now be set dynamically with setNumCapabilities from the same.

    0 讨论(0)
  • 2021-02-13 06:29

    It is GHC.Conc.getNumProcessors :: IO Int getNumCapabilities tells how many threads are suggested to GHC (and depends on +RTS -N option parameter.)

    0 讨论(0)
  • 2021-02-13 06:31

    You could copy'n'paste this code into a file called numCores and compile it with your Haskell code. Than you can use the FFI to import its definition and use it directly in your Haskell code:

    {-# LANGUAGE ForeignFunctionInterface #-}
    import Control.Applicative ((<$>))
    import Foreign.C.Types (CInt)
    
    foreign import ccall "getNumCores" c_getNumCores :: IO CInt
    getNumCores :: IO Int
    getNumCores = fromEnum <$> c_getNumCores
    
    0 讨论(0)
  • 2021-02-13 06:32

    Yes, there is such a method. Code from "Real World Haskell": http://book.realworldhaskell.org/read/concurrent-and-multicore-programming.html

    import GHC.Conc (numCapabilities)
    
    main = putStrLn $ "number of cores: " ++ show numCapabilities
    
    0 讨论(0)
  • 2021-02-13 06:34

    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
    
    0 讨论(0)
提交回复
热议问题