Alternative method to avoid rand contention in highly parallel usage #2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
While this hasn't been a real-world performance issue in my particular use case, it is a known theoretical issue with this library that the usage of global rand, while convenient for users of the API, could cause lock contention and therefore performance issues when doing selection across multiple goroutines simultaneously in high throughput situations. Since more people seem to be adopting usage of this library, it's worth taking a look.
Initial Profiling
Adding a new appropriate RunParallel benchmark and checking across different CPU counts can show us the impact of this:
Regardless of the number of Choices, as we increase the number of parallel CPUs attempting to utilize a Chooser simultaneously, performance decreases rather than increases. In practice, going from 1 CPU to 16 CPUs more than halves the actual throughput.
Using CPU profiling and examining the 16 CPU benchmark run via
pprof
confirms lock contention is indeed blocking compute quite significantly during this highly parallel utilization:Patch and Benchmarks
This PR introduces a
PickSource(*rand.Rand)
method, a new version ofPick()
which a reference to a source of randomness allows us to create a thread-local unique rand source per thread and avoid locks entirely. Now, as we add more CPUs, we can scale workload. The performance impact as shown in this benchmark is quite significant (~2x at 2 CPUs, ~20x at 16 CPUs):Time is again being spent as it should be:
Considerations
Adding a new method complicates the API, especially since it is one that opens the door to potential mis-use from developers who are not familiar with the underlying safety issues. Additionally, it is still unconfirmed whether any users of this library currently have a highly parallel utilization need.
If this is merged, I should make it clear in the documentation the situations where this method should be utilized and provide appropriate sample code so that it can be used safely.