Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Increase speed by changing some maps to arrays #21

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion diag/perft.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func perftBreakdown(G *chess.Game, depth int) (nodes, checks, castles, mates, ca
}

toMove := G.ActiveColor()
notToMove := []piece.Color{game.Black, game.White}[toMove]
notToMove := piece.OtherColor[toMove]

isChecked := G.Check(toMove)
ml := G.LegalMoves()
Expand Down
50 changes: 48 additions & 2 deletions diag/perftsuite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ package diag
import (
"errors"
"fmt"
"github.com/andrewbackes/chess/epd"
"github.com/andrewbackes/chess/position"
"os"
"strconv"
"strings"
"testing"
"time"

"github.com/andrewbackes/chess/epd"
"github.com/andrewbackes/chess/position"
)

func TestPerftSuite(t *testing.T) {
Expand Down Expand Up @@ -127,3 +128,48 @@ func checkPerft(p *position.Position, depth int, nodes uint64) error {
}
return nil
}

func BenchmarkPerftSuite(b *testing.B) {
f, err := os.Open("perftsuite.epd")
if err != nil {
b.Fatal(err)
}
tests, err := epd.Read(f)
if err != nil {
b.Fatal(err)
}

maxdepth := 3
tests = tests[:10]
if strings.ToLower(os.Getenv("BENCH_DEEP_PERFT_SUITE")) == "true" {
maxdepth = 5
} else if testing.Short() {
tests = tests[:5]
maxdepth = 1
}
for i, test := range tests {
if len(test.Operations) > maxdepth+1 {
test.Operations = test.Operations[:maxdepth+1]
}

b.Run(fmt.Sprintf("EPD_%02d", i+1), func(b *testing.B) {
benchPerftSuite(b, test)
})
}
}

func benchPerftSuite(b *testing.B, test *epd.EPD) {
for depth := range test.Operations {
if depth == 0 {
// Perft with any position and depth 0 always returns 1. Don't need to bench.
continue
}

b.Run(fmt.Sprint("Depth ", depth), func(b *testing.B) {
for i := 0; i < b.N; i++ {
// No need to check result, this is done in TestPerftSuite.
Perft(test.Position, depth)
}
})
}
}
185 changes: 135 additions & 50 deletions game/game_test.go

Large diffs are not rendered by default.

17 changes: 12 additions & 5 deletions piece/color.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,21 @@ const (
NoColor Color = 2
)

const COLOR_COUNT = 2

// Colors can be used to loop through the colors via range.
var Colors = [2]Color{White, Black}
var Colors = [COLOR_COUNT]Color{White, Black}

// OtherColor can be used to get opponent's color. E.g. `oponentColor := piece.OtherColor[position.ActiveColor]`.
var OtherColor = [COLOR_COUNT]Color{Black, White}

var colorStrings = [COLOR_COUNT]string{"White", "Black"}

func (c Color) String() string {
return map[Color]string{
White: "White",
Black: "Black",
}[c]
if c >= COLOR_COUNT {
return ""
}
return colorStrings[c]
}

func (c Color) MarshalJSON() ([]byte, error) {
Expand Down
47 changes: 47 additions & 0 deletions piece/color_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package piece

import "testing"

func TestColorString(t *testing.T) {
testCases := []struct {
name string
c Color
want string
}{
{"White", White, "White"},
{"Black", Black, "Black"},
{"NoColor", NoColor, ""},
{"Color(4)", Color(4), ""},
//{"Color(-1)", Color(-1), ""}, // Build error: constant -1 overflows Color.
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if s := tc.c.String(); s != tc.want {
t.Errorf("%#v.String() = %s, want %s", tc.c, s, tc.want)
}
})
}
}

const benchValidColorCount = 2 // White, Black.

func BenchmarkColorString(b *testing.B) {
b.Run("Valid-Colors", func(b *testing.B) {
for i := 0; i < b.N; i++ {
// Is Color(0), Color(1), Color(0), Color(1), ...
s := Color(i % benchValidColorCount).String()
if s == "" {
b.Fatal("Valid color should not have a empty string output")
}
}
})
b.Run("Invalid-Colors", func(b *testing.B) {
for i := 0; i < b.N; i++ {
// Is Color(2), Color(3), Color(2), Color(3), ...
s := Color(benchValidColorCount + i%benchValidColorCount).String()
if s != "" {
b.Fatal("Invalid color should have a empty string output")
}
}
})
}
30 changes: 17 additions & 13 deletions piece/piece.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
// Type is a player's piece. Ex: King, Queen, etc.
type Type uint8

const TYPE_COUNT = 7 // Including piece.None. Improves code readability.

// Possible pieces.
const (
None Type = iota
Expand All @@ -19,16 +21,13 @@ const (
King
)

var typeStrings = [TYPE_COUNT]string{" ", "p", "n", "b", "r", "q", "k"}

func (T Type) String() string {
return map[Type]string{
None: " ",
Pawn: "p",
Knight: "n",
Bishop: "b",
Rook: "r",
Queen: "q",
King: "k",
}[T]
if T >= TYPE_COUNT {
return ""
}
return typeStrings[T]
}

// Piece represents a chess piece.
Expand All @@ -46,15 +45,20 @@ func (P Piece) String() string {
return t
}

var figurines = [COLOR_COUNT][TYPE_COUNT]rune{
[TYPE_COUNT]rune{' ', 0x2659, 0x2658, 0x2657, 0x2656, 0x2655, 0x2654},
[TYPE_COUNT]rune{' ', 0x265F, 0x265E, 0x265D, 0x265C, 0x265B, 0x265A},
}

// Figurine returns a chess piece icon
func (P Piece) Figurine() string {
if P.Color == NoColor || P.Type == None {
return " "
}
return string(map[Color]map[Type]rune{
White: {Pawn: 0x2659, Knight: 0x2658, Bishop: 0x2657, Rook: 0x2656, Queen: 0x2655, King: 0x2654},
Black: {Pawn: 0x265F, Knight: 0x265E, Bishop: 0x265D, Rook: 0x265C, Queen: 0x265B, King: 0x265A},
}[P.Color][P.Type])
if P.Color >= COLOR_COUNT || P.Type >= TYPE_COUNT {
return "\x00"
}
return string(figurines[P.Color][P.Type])
}

// New returns a new chess piece type.
Expand Down
170 changes: 162 additions & 8 deletions piece/piece_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,181 @@ package piece
import (
"encoding/json"
"fmt"
"github.com/stretchr/testify/assert"
"reflect"
"testing"
)

func TestPiecePrint(t *testing.T) {
p := New(White, Pawn)
if fmt.Sprint(p) != "P" {
t.Fail()
testCases := []struct {
name string
p Piece
want string
}{
{"White-Pawn", New(White, Pawn), "P"},
{"Black-Pawn", New(Black, Pawn), "p"},
{"NoColor-Pawn", New(NoColor, Pawn), "p"},
{"Color(4)-Pawn", New(Color(4), Pawn), "p"},
{"White-None", New(White, None), " "},
{"Black-None", New(Black, None), " "},
{"NoColor-None", New(NoColor, None), " "},
{"Color(4)-None", New(Color(4), None), " "},
{"White-Rook", New(White, Rook), "R"},
{"Black-Queen", New(Black, Queen), "q"},
{"NoColor-Knight", New(NoColor, Knight), "n"},
{"Color(4)-King", New(Color(4), King), "k"},
{"White-Type(10)", New(White, Type(10)), ""},
{"Black-Type(10)", New(Black, Type(10)), ""},
{"NoColor-Type(10)", New(NoColor, Type(10)), ""},
{"Color(4)-Type(10)", New(Color(4), Type(10)), ""},
//{"Color(-1)-Type(-1)", New(Color(-1), Type(-1)), ""}, // Build error: constant -1 overflows Color/Type.
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if s := fmt.Sprint(tc.p); s != tc.want {
t.Errorf("%#v.String() = %#v, want %#v", tc.p, s, tc.want)
}
})
}
}

func TestColorUnmarshalJson(t *testing.T) {
blob := `["White"]`
want := []Color{White}
var c []Color
json.Unmarshal([]byte(blob), &c)
assert.Equal(t, []Color{White}, c)
err := json.Unmarshal([]byte(blob), &c)
if err != nil || !reflect.DeepEqual(c, want) {
t.Fatalf("json.Unmarshal(%#v, &c) = %#v, want %#v", blob, err, error(nil))
} else if !reflect.DeepEqual(c, want) {
t.Fatalf("json.Unmarshal(%#v, &c); c = %#v, want %#v", blob, c, want)
}
}

func TestColorMarshalJson(t *testing.T) {
j := []Color{White}
want := `["White"]`
result, err := json.Marshal(j)
assert.Equal(t, nil, err)
assert.Equal(t, `["White"]`, string(result))
if err != nil || string(result) != want {
t.Fatalf("json.Marshal(%#v) = (%s, %#v), want (%s, %#v)", j, result, err, want, error(nil))
}
}

func TestTypeString(t *testing.T) {
testCases := []struct {
name string
ty Type
want string
}{
{"Pawn", Pawn, "p"},
{"Rook", Rook, "r"},
{"King", King, "k"},
{"None", None, " "},
{"Type(10)", Type(10), ""},
//{"Type(-1)", Type(-1), ""}, // Build error: constant -1 overflows Type.
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if s := tc.ty.String(); s != tc.want {
t.Errorf("%#v.String() = %#v, want %#v", tc.ty, s, tc.want)
}
})
}
}

func TestPieceFigurine(t *testing.T) {
testCases := []struct {
name string
p Piece
want string
}{
{"White-Pawn", New(White, Pawn), "♙"},
{"Black-Pawn", New(Black, Pawn), "♟"},
{"NoColor-Pawn", New(NoColor, Pawn), " "},
{"Black-None", New(Black, None), " "},
{"NoColor-None", New(NoColor, None), " "},
{"Color(4)-Pawn", New(Color(4), Pawn), "\x00"},
{"Black-Type(10)", New(Black, Type(10)), "\x00"},
{"Color(4)-Type(10)", New(Color(4), Type(10)), "\x00"},
//{"Color(-1)-Type(-1)", New(Color(-1), Type(-1)), ""}, // Build error: constant -1 overflows Color/Type.
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if f := tc.p.Figurine(); f != tc.want {
t.Errorf("%#v.Figurine() = %#v, want %#v", tc.p, f, tc.want)
}
})
}
}

const benchValidTypesCount = 7 // None, Pawn, ..., King.

func BenchmarkTypeString(b *testing.B) {
b.Run("Valid-Types", func(b *testing.B) {
for i := 0; i < b.N; i++ {
// Is Type(0), Type(1), ..., Type(6), Type(0), Type(1), ...
s := Type(i % benchValidTypesCount).String()
if s == "" {
b.Fatal("Valid type should not have a empty string output")
}
}
})
b.Run("Invalid-Types", func(b *testing.B) {
for i := 0; i < b.N; i++ {
// Is Type(7), Type(8), ..., Type(13), Type(7), Type(8), ...
s := Type(benchValidTypesCount + i%benchValidTypesCount).String()
if s != "" {
b.Fatal("Invalid type should have a empty string output")
}
}
})
}

func BenchmarkPieceFigurine(b *testing.B) {
b.Run("Valid-Colors_Valid-Types", func(b *testing.B) {
for i := 0; i < b.N; i++ {
// In the piece following colors and types are present.
// Color(0), Color(1), Color(2), Color(0), Color(1), Color(2), ...
// Type(0), Type(1), ..., Type(6), Type(0), Type(1), ...
p := Piece{Color(i % benchValidColorCount), Type(i % benchValidTypesCount)}
s := p.Figurine()
if s == "\x00" {
b.Fatalf("Figurine of piece with valid color and type %#v should not have an empty string output", p)
}
}
})
b.Run("Invalid-Colors_Valid-Types", func(b *testing.B) {
for i := 0; i < b.N; i++ {
// In the piece following colors and types are present.
// Color(3), Color(4), Color(5), Color(3), Color(4), Color(5), ...
// Type(0), Type(1), ..., Type(6), Type(0), Type(1), ...
p := Piece{Color(benchValidColorCount + i%benchValidColorCount), Type(i % benchValidTypesCount)}
s := p.Figurine()
if s != "\x00" && s != " " {
b.Fatalf("Figurine of piece with invalid color and valid type %#v, should have an empty string output, got: %#v", p, s)
}
}
})
b.Run("Valid-Colors_Invalid-Types", func(b *testing.B) {
for i := 0; i < b.N; i++ {
// In the piece following colors and types are present.
// Color(0), Color(1), Color(2), Color(0), Color(1), Color(2), ...
// Type(7), Type(8), ..., Type(13), Type(7), Type(8), ...
p := Piece{Color(i % benchValidColorCount), Type(benchValidTypesCount + i%benchValidTypesCount)}
s := p.Figurine()
if s != "\x00" && s != " " {
b.Fatalf("Figurine of piece with valid color and invalid type %#v should have an empty string output, got: %#v", p, s)
}
}
})
b.Run("Invalid-Colors_Invalid-Types", func(b *testing.B) {
for i := 0; i < b.N; i++ {
// In the piece following colors and types are present.
// Color(3), Color(4), Color(5), Color(0), Color(1), Color(2), ...
// Type(7), Type(8), ..., Type(13), Type(7), Type(8), ...
p := Piece{Color(benchValidColorCount + i%benchValidColorCount), Type(benchValidTypesCount + i%benchValidTypesCount)}
s := p.Figurine()
if s != "\x00" && s != " " {
b.Fatalf("Figurine of piece with invalid color and type %#v should have an empty string output, got: %#v", p, s)
}
}
})
}
Loading