summaryrefslogtreecommitdiff
path: root/queue
diff options
context:
space:
mode:
authorPaul Buetow <pbuetow@mimecast.com>2020-08-24 14:44:34 +0100
committerPaul Buetow <pbuetow@mimecast.com>2020-08-24 14:44:34 +0100
commit24996416c11942abe22b1e3c1dee29243fd55fd1 (patch)
treeb090eb27d9aabe9ff7e61cc3caf79ef6c778d3f0 /queue
parent4098a882ca0dfa1f785ecf5800cb1efcbcfe44a4 (diff)
benchmark of pq
Diffstat (limited to 'queue')
-rw-r--r--queue/elementarypq.go9
-rw-r--r--queue/pq.go1
-rw-r--r--queue/pq_test.go37
3 files changed, 44 insertions, 3 deletions
diff --git a/queue/elementarypq.go b/queue/elementarypq.go
index 31cab9f..1155cb4 100644
--- a/queue/elementarypq.go
+++ b/queue/elementarypq.go
@@ -5,10 +5,12 @@ import "algorithms/ds"
type ElementaryPQ struct {
a ds.ArrayList
size int
+ // Initial capacity
+ capacity int
}
func NewElementaryPQ(capacity int) ElementaryPQ {
- return ElementaryPQ{make(ds.ArrayList, 0, capacity), 0}
+ return ElementaryPQ{make(ds.ArrayList, 0, capacity), 0, capacity}
}
func (q ElementaryPQ) Insert(a int) {
@@ -43,6 +45,11 @@ func (q ElementaryPQ) Size() int {
return q.size
}
+func (q ElementaryPQ) Clear() {
+ q.size = 0
+ q.a = make(ds.ArrayList, 0, q.capacity)
+}
+
func (q ElementaryPQ) max() (ind, max int) {
for i, a := range q.a {
if a > max {
diff --git a/queue/pq.go b/queue/pq.go
index ecf54c8..5f2079a 100644
--- a/queue/pq.go
+++ b/queue/pq.go
@@ -6,4 +6,5 @@ type PQ interface {
DeleteMax() int
Empty() bool
Size() int
+ Clear()
}
diff --git a/queue/pq_test.go b/queue/pq_test.go
index 35e12fd..0b13144 100644
--- a/queue/pq_test.go
+++ b/queue/pq_test.go
@@ -7,8 +7,8 @@ import (
)
const minLength int = 1
-const maxLength int = 1000
-const factor int = 10
+const maxLength int = 10000
+const factor int = 100
func TestElementaryPQ(t *testing.T) {
q := NewElementaryPQ(1)
@@ -40,3 +40,36 @@ func test(q PQ, l int, t *testing.T) {
}
t.Run(fmt.Sprintf("%d", l), cb)
}
+
+func BenchmarkElementaryPQ(b *testing.B) {
+ q := NewElementaryPQ(1)
+ for i := minLength; i <= maxLength; i *= factor {
+ benchmark(q, i, b)
+ }
+}
+
+func benchmark(q PQ, l int, b *testing.B) {
+ r := ds.NewRandomArrayList(l, -1)
+ aux := ds.NewArrayList(l)
+
+ b.Run(fmt.Sprintf("randomInsert(%d)", l), func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ q.Clear()
+ for _, a := range r {
+ q.Insert(a)
+ }
+ }
+ })
+
+ b.Run(fmt.Sprintf("randomInsertAndDeleteMax(%d)", l), func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ q.Clear()
+ for _, a := range r {
+ q.Insert(a)
+ }
+ for i := 0; !q.Empty(); i++ {
+ aux[i] = q.DeleteMax()
+ }
+ }
+ })
+}