https://github.com/smallnest/weighted
high-performance common weighted algorithm library
https://github.com/smallnest/weighted
algortihm weight
Last synced: about 1 year ago
JSON representation
high-performance common weighted algorithm library
- Host: GitHub
- URL: https://github.com/smallnest/weighted
- Owner: smallnest
- License: apache-2.0
- Created: 2016-12-01T02:32:32.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2023-04-19T05:54:10.000Z (about 3 years ago)
- Last Synced: 2025-03-29T04:11:48.394Z (about 1 year ago)
- Topics: algortihm, weight
- Language: Go
- Homepage:
- Size: 26.4 KB
- Stars: 202
- Watchers: 9
- Forks: 43
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://opensource.org/licenses/Apache-2.0) [](http://godoc.org/github.com/smallnest/weighted) [](https://travis-ci.org/smallnest/weighted) [](https://coveralls.io/github/smallnest/weighted?branch=master) [](https://goreportcard.com/report/github.com/smallnest/weighted)
**rust version**: [weighted-rs](https://github.com/smallnest/weighted-rs)
Package **weighted** implements the smooth weighted round-robin balancing algorithm. This algorithm is implemented in Nginx:
https://github.com/phusion/nginx/commit/27e94984486058d73157038f7950a0a36ecc6e35.
**Notice**: The weighted is NOT goroutine-safe so you MUST use the synchronization primitive to protect it (the Next method) in concurrent cases.
Algorithm is as follows: on each peer selection we increase current_weight
of each eligible peer by its weight, select peer with greatest current_weight
and reduce its current_weight by total number of weight points distributed
among peers.
In case of { 5, 1, 1 } weights this gives the following sequence of
current_weight's: (a, a, b, a, c, a, a)
This is an example to use it:
```go
package main
import "fmt"
func ExampleSW_Next() {
w := &SW{}
w.Add("a", 5)
w.Add("b", 2)
w.Add("c", 3)
for i := 0; i < 10; i++ {
fmt.Printf("%s ", w.Next())
}
}
```
And this lib has provides another weighted round robin algorithm. This algorithm is used in [LVS](http://kb.linuxvirtualserver.org/wiki/Weighted_Round-Robin_Scheduling).
It has better performance but it is not so more smooth than the first algorithm, so you can select one algorithm according to your case. It is used like the first:
```go
package main
import "fmt"
func ExampleRRW_Next() {
w := &RRW{}
w.Add("a", 5)
w.Add("b", 2)
w.Add("c", 3)
for i := 0; i < 10; i++ {
fmt.Printf("%s ", w.Next())
}
}
```