Added benchmarks

This commit is contained in:
Eduard Urbach 2023-07-06 19:40:33 +02:00
parent 9b956ac441
commit c3e12a7663
Signed by: akyoto
GPG Key ID: C874F672B1AF20C0
3 changed files with 92 additions and 2 deletions

View File

@ -89,6 +89,10 @@ func (c *collection[T]) Set(key string, value *T) {
// Delete deletes a key from the collection. // Delete deletes a key from the collection.
func (c *collection[T]) Delete(key string) { func (c *collection[T]) Delete(key string) {
if !c.Exists(key) {
return
}
c.data.Delete(key) c.data.Delete(key)
os.Remove(c.keyFile(key)) os.Remove(c.keyFile(key))
} }

View File

@ -1,6 +1,7 @@
package ocean_test package ocean_test
import ( import (
"sync"
"testing" "testing"
"git.akyoto.dev/go/assert" "git.akyoto.dev/go/assert"
@ -88,3 +89,88 @@ func TestPersistence(t *testing.T) {
assert.NotNil(t, user1) assert.NotNil(t, user1)
assert.NotNil(t, user2) assert.NotNil(t, user2)
} }
func TestParallel(t *testing.T) {
users, err := ocean.New[User]("test")
assert.Nil(t, err)
defer users.Clear()
users.Set("1", &User{Name: "User 1"})
wg := sync.WaitGroup{}
for i := 0; i < 100; i++ {
wg.Add(2)
go func() {
defer wg.Done()
user, err := users.Get("1")
assert.Nil(t, err)
assert.NotNil(t, user)
assert.Equal(t, user.Name, "User 1")
}()
go func() {
defer wg.Done()
users.Set("1", &User{Name: "User 1"})
}()
}
wg.Wait()
}
func BenchmarkGet(b *testing.B) {
users, err := ocean.New[User]("test")
assert.Nil(b, err)
defer users.Clear()
users.Set("1", &User{Name: "User 1"})
b.ReportAllocs()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_, err := users.Get("1")
if err != nil {
b.Fail()
}
}
})
b.StopTimer()
}
func BenchmarkSet(b *testing.B) {
users, err := ocean.New[User]("test")
assert.Nil(b, err)
defer users.Clear()
user := &User{Name: "User 1"}
b.ReportAllocs()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
users.Set("1", user)
}
})
b.StopTimer()
}
func BenchmarkDelete(b *testing.B) {
users, err := ocean.New[User]("test")
assert.Nil(b, err)
defer users.Clear()
b.ReportAllocs()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
users.Delete("1")
}
})
b.StopTimer()
}

View File

@ -21,7 +21,7 @@ type User struct {
// Load existing data from ~/.ocean/User/ // Load existing data from ~/.ocean/User/
users := ocean.New[User]() users := ocean.New[User]()
// Store in memory and also store in ~/.ocean/User/1.json // Store in memory and also store in ~/.ocean/User/1
users.Set("1", &User{Name: "User 1"}) users.Set("1", &User{Name: "User 1"})
// Read from memory // Read from memory