Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check whether evenI is still faster than even #99

Closed
Bodigrim opened this issue Mar 17, 2018 · 3 comments
Closed

Check whether evenI is still faster than even #99

Bodigrim opened this issue Mar 17, 2018 · 3 comments

Comments

@Bodigrim
Copy link
Owner

Module Math.NumberTheory.Moduli.Jacobi contains an interesting helper function:

-- For large Integers, going via Int is much faster than bit-fiddling
-- on the Integer, so we do that.
evenI :: Integral a => a -> Bool
evenI n = fromIntegral n .&. 1 == (0 :: Int)

Actually, it was definitely much faster than even from Prelude before GHC 8.4 due to trac 14437. We should check (looking at Core and CMM), whether evenI is still faster. And if it is, push its definition into base for the profit of the whole community.

@Bodigrim
Copy link
Owner Author

Unexpectedly, evenI appears much faster than even from Prelude.

import Data.Time.Clock

evenI :: Integer -> Bool
evenI n = fromIntegral n `rem` 2 == (0 :: Word)

lim :: Integer
lim = 100000000

main :: IO ()
main = do
  t0 <- getCurrentTime
  print $ maximum $ filter even [1..lim]
  t1 <- getCurrentTime
  putStrLn "even"
  print $ diffUTCTime t1 t0

  t0 <- getCurrentTime
  print $ maximum $ filter evenI [1..lim]
  t1 <- getCurrentTime
  putStrLn "evenI"
  print $ diffUTCTime t1 t0

With GHC 8.4.1:

$ ghc -O2 Even.hs
[1 of 1] Compiling Main             ( Even.hs, Even.o )
Linking Even ...
$ ./Even
100000000
even
6.367393s
100000000
evenI
4.35664s

I looked into CMM. Prelude.even results in remInteger n 2, which is left as is. On contrary, fromIntegral :: Integer -> Word is very cheap and remWord n 2 is optimised to bitwise and.

I'll file a ticket in GHC trac.

@Bodigrim
Copy link
Owner Author

@Bodigrim
Copy link
Owner Author

Bodigrim commented Jul 6, 2018

Anyway, evenI has been refactored in #103 and is in line with rem4is3 and rem8is1or7, so closing.

@Bodigrim Bodigrim closed this as completed Jul 6, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant