[racket] Untyped arithmetics performance
Adding two fractions with different denominators requires a computation
of the common denominator. For large denominators this can take time.
The time needed to compute your sum will depend on the order of the terms.
If you only need an inexact result, then use floating points:
(for/sum ([x (in-range 10000)]) (/ x (- 10000. x)))))
Note the dot after 10000.
/Jens Axel
2015-01-24 17:39 GMT+01:00 Daniel Kvasnička <daniel.kvasnicka at me.com>:
> Hi, I'm observing the following difference in performance:
>
>> (time (exact->inexact (for/sum ([x (in-range 10000)]) (/ x 10000))))
> cpu time: 6 real time: 6 gc time: 0
> 4999.5
>> (time (exact->inexact (for/sum ([x (in-range 10000)]) (/ x (- 10000 x)))))
> cpu time: 3624 real time: 3622 gc time: 39
> 87876.06036044382
>
> The difference seems huge to me and I'm wondering whether it's "normal" and what are the right tools to overcome it.
> If I understand it correctly, it's about contract checking and the fact that there is one more math opeartion involved does not in itself lead to such difference. The division operator needs to be sure that the outcome of the minus op. is of the right type, is that correct?
>
> If so -- and the increase in time cannot be considered a "bug" -- what is the right way to get around that. I've employed 2 ways: Typed Racket and switching the portion of code to racket/flonum. Both of these approaches resulted in big perf. improvement and basically make the computation instant again. Are these the right, "rackety", solutions? I've also tried to use unchecked ops but Racket 6.1.1 is constantly segfaulting on me when running this (from my digging I think unsafe-fl/ is what segfaults it):
>
> (time (exact->inexact (for/sum ([x (in-range 10000)]) (unsafe-fl/ (->fl x) (unsafe-fx- 10000 x)))))
>
> Daniel
> ____________________
> Racket Users list:
> http://lists.racket-lang.org/users
--
--
Jens Axel Søgaard