Created
September 7, 2015 14:26
-
-
Save FZambia/2dc7c2f33cce44209689 to your computer and use it in GitHub Desktop.
Performance degradation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"testing" | |
"time" | |
"github.com/centrifugal/centrifugo/libcentrifugo/stringqueue" | |
) | |
type Session struct{} | |
func (t *Session) Send(msg string) error { | |
// Do nothing, just return nil. | |
return nil | |
} | |
type Client struct { | |
messages stringqueue.StringQueue | |
session *Session | |
} | |
func NewClient() *Client { | |
c := Client{ | |
messages: stringqueue.New(), | |
session: &Session{}, | |
} | |
go c.sendIntoSessionFromQueue() | |
return &c | |
} | |
func (c *Client) Add(message string) error { | |
ok := c.messages.Add(message) | |
if !ok { | |
return errors.New("client closed") | |
} | |
return nil | |
} | |
func (c *Client) sendIntoSessionFromQueue() { | |
for { | |
msg, ok := c.messages.Wait() | |
if !ok { | |
if c.messages.Closed() { | |
return | |
} | |
continue | |
} | |
err := c.sendTimeout(msg) | |
if err != nil { | |
// Close client here. | |
println(err.Error()) | |
} | |
} | |
} | |
func (c *Client) sendTimeout(msg string) error { | |
to := time.After(time.Second * time.Duration(5)) | |
sent := make(chan error) | |
go func() { | |
sent <- c.session.Send(msg) | |
}() | |
select { | |
case err := <-sent: | |
return err | |
case <-to: | |
return errors.New("send timed out") | |
} | |
panic("unreachable") | |
} | |
func BenchmarkClient(b *testing.B) { | |
clients := []*Client{} | |
numClients := 100 | |
numMessages := 1000 | |
for i := 0; i < numClients; i++ { | |
clients = append(clients, NewClient()) | |
} | |
b.ResetTimer() | |
for n := 0; n < b.N; n++ { | |
for i := 0; i < numMessages; i++ { | |
for _, client := range clients { | |
client.Add("benchmarking") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment