# Speed issue with KahanSummation

**URL:** <https://discourse.julialang.org/t/speed-issue-with-kahansummation/75491>\
**Category:** Performance\
**Tags:** question, package, parallel\
**Created:** [January 31, 2022, 6:29am UTC](https://discourse.julialang.org/t/speed-issue-with-kahansummation/75491 "2022-01-31T06:29:26Z")\
**Posts on this page:** 1\
**Showing post:** 11

<div class="post-metadata">

**Author:** ![HJW019](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hjw019/32/22102_2.png) [@HJW019](https://discourse.julialang.org/u/HJW019)\
**Post date:** [February 3, 2022, 9:42am UTC](https://discourse.julialang.org/t/speed-issue-with-kahansummation/75491/11 "2022-02-03T09:42:22Z")

</div>

@goerch PM’d me another solution of doing multi-threading Kahan summation based on KahanSummation.jl. It looks much more elegant and I don’t think @goerch would mind me sharing it here.

(Note that AccurateArithmetic.jl and KahanSummation.jl both export `sum_kbn()`. This post is about the function from KahanSummation.)

It is based on a patch of KahanSummation [here](https://github.com/JuliaMath/KahanSummation.jl/pull/7/files). The patch has an outdated function `mapreduce_single` which has to be replaced by `mapreduce_first` for recent versions of Julia. After the update, the content could be loaded using `include("..")`. I made the package readily available on [this page](https://github.com/HJW019/KahanSummation.jl); search for the file name `KahanSummation_patch.jl`.

After loading, @goerch showed that it could be extended to construct a multi-threading (or, parallel) function as follows.

```julia
using InitialValues, Folds

include("KahanSummation_patch.jl")
psum_kbn(f, X) = singleprec(Folds.mapreduce(f, InitialValues.asmonoid(plus_kbn), X))
psum_kbn(X) = psum_kbn(identity, X)

```

The use of `psum_kbn()` is just the same as `sum_kbn()` and it is much faster.

So, there are currently a couple of high precision summation functions in Julia. In terms of speed, the rank is (slow to fast):

`KahanSummation.sum_kbn()`: \< `psum_kbn()` \< `AccurateArithmetic.sum_kbn()` = `AccurateArithmetic.sum_oro()`

I believe they are very useful for many applications. However, only `KahanSummation.sum_kbn()`, the slowest variant, is compatible with the AD package ForwardDiff.jl. I am [starting another thread](https://discourse.julialang.org/t/high-precision-summation-functions-not-compatible-with-optim-jl-with-autodiff-forward/75714) to discuss the issue.

---

_[View the full topic](https://discourse.julialang.org/t/speed-issue-with-kahansummation/75491)._
