Files
wuffs/lang/check/gen.go
T
Nigel Tao 3338d6d1bc Write LZW output 8 bytes at a time, not 1
The benchmarks are mixed, but I think it's still a net win.

----
name                                    old speed     new speed     delta

wuffs_gif_decode_1k_bw/clang            258MB/s ± 0%  253MB/s ± 1%    -2.04%  (p=0.008 n=5+5)
wuffs_gif_decode_1k_color/clang         159MB/s ± 0%  116MB/s ± 0%   -26.76%  (p=0.008 n=5+5)
wuffs_gif_decode_10k/clang              167MB/s ± 0%  138MB/s ± 0%   -17.42%  (p=0.008 n=5+5)
wuffs_gif_decode_100k_artificial/clang  205MB/s ± 0%  439MB/s ± 0%  +114.53%  (p=0.008 n=5+5)
wuffs_gif_decode_100k_realistic/clang   151MB/s ± 0%  164MB/s ± 0%    +8.41%  (p=0.008 n=5+5)
wuffs_gif_decode_1000k/clang            155MB/s ± 0%  165MB/s ± 0%    +6.50%  (p=0.008 n=5+5)
wuffs_gif_decode_anim_screencap/clang   255MB/s ± 0%  921MB/s ± 0%  +261.50%  (p=0.008 n=5+5)

wuffs_gif_decode_1k_bw/gcc              316MB/s ± 2%  267MB/s ± 1%   -15.78%  (p=0.008 n=5+5)
wuffs_gif_decode_1k_color/gcc           184MB/s ± 1%  134MB/s ± 0%   -27.57%  (p=0.008 n=5+5)
wuffs_gif_decode_10k/gcc                196MB/s ± 0%  161MB/s ± 0%   -17.50%  (p=0.008 n=5+5)
wuffs_gif_decode_100k_artificial/gcc    287MB/s ± 0%  449MB/s ± 1%   +56.22%  (p=0.008 n=5+5)
wuffs_gif_decode_100k_realistic/gcc     182MB/s ± 0%  182MB/s ± 1%      ~     (p=0.690 n=5+5)
wuffs_gif_decode_1000k/gcc              187MB/s ± 1%  185MB/s ± 1%      ~     (p=0.056 n=5+5)
wuffs_gif_decode_anim_screencap/gcc     397MB/s ± 0%  973MB/s ± 0%  +145.42%  (p=0.008 n=5+5)

wuffs_lzw_decode_20k/clang              170MB/s ± 0%  191MB/s ± 1%   +12.52%  (p=0.008 n=5+5)
wuffs_lzw_decode_100k/clang             242MB/s ± 0%  312MB/s ± 2%   +29.00%  (p=0.008 n=5+5)

wuffs_lzw_decode_20k/gcc                220MB/s ± 0%  227MB/s ± 0%    +3.31%  (p=0.008 n=5+5)
wuffs_lzw_decode_100k/gcc               317MB/s ± 0%  369MB/s ± 1%   +16.53%  (p=0.008 n=5+5)
----

LZW is the compression method used by GIF images. Roughly speaking, LZW
is a sequence of codes, and each code emits either 1 byte (a literal
code) or multiple bytes (a copy code). The speed gain in this commit
comes from, when emitting an N-byte copy code, this now requires N/8
iterations instead of N iterations, as each iteration now writes 8 bytes
instead of 1. Literal codes, both before and after this commit, requires
a single iteration.

Decoding should therefore get faster or slower depending on whether it's
copy-code-heavy or literal-code-heavy respectively. For what it's worth,
copy-code-heavy GIF images also usually compress better.

Running script/extract-giflzw.go (or examining the cached output at
test/data/analysis/giflzw-emission-lengths.txt) on the anim_screencap
(which got faster) and 1k_color (which got slower) cases (also known as
gifplayer-muybridge.gif and hippopotamus.regular.gif) shows that the
proportion of literal codes agrees with that explanation.

----
gifplayer-muybridge.gif (all frames)
 Percent   Count  Emission_Length_Bucket
   12.78   34658           1 (Literal Code)
   14.05   38106           2
   13.25   35937           3
   10.59   28707           4
    7.85   21286           5
    6.08   16481           6
    4.85   13156           7
    3.60    9764           8
    9.34   25318    9 ..  16
    4.89   13257   17 ..  32
    4.78   12954   33 ..  64
    4.72   12806   65 .. 128
    3.02    8190  127 .. 256
    0.20     550  256+

hippopotamus.regular.gif (all frames)
 Percent   Count  Emission_Length_Bucket
   82.66     672           1 (Literal Code)
   13.04     106           2
    2.83      23           3
    0.86       7           4
    0.37       3           5
    0.25       2           6
    0.00       0           7
    0.00       0           8
    0.00       0    9 ..  16
    0.00       0   17 ..  32
    0.00       0   33 ..  64
    0.00       0   65 .. 128
    0.00       0  127 .. 256
    0.00       0  256+
----

The new algorithm also adds more CPU and RAM overhead, regardless of
whether the input GIF image's LZW data is copy-code-heavy or
literal-code-heavy. For example, the suffix table grows by 8x, from 4KiB
to 32 KiB.

The gifplayer-muybridge.gif image is also larger (472 x 298) and the
hippopotamus.regular.gif image is also smaller (36 x 28). Higher fixed
costs may have larger (negative) relative effects on decoding smaller
images.

To repeat, I think it's still a net win.

An upcoming commit will update the std/lzw/README.md file to provide
more detail on the algorithm.

Thanks to Tushar Khandelwal for the idea.
2018-10-21 14:48:40 +11:00

360 lines
7.6 KiB
Go

// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build ignore
package main
// gen.go generates data.go.
//
// Invoke it via "go generate".
import (
"bytes"
"fmt"
"go/format"
"io/ioutil"
"os"
"sort"
"strings"
)
var reasons = [...]string{
"a < b: b > a",
"a < b: a < c; c < b",
"a < b: a < c; c == b",
"a < b: a == c; c < b",
"a < b: a < c; c <= b",
"a < b: a <= c; c < b",
"a > b: b < a",
"a <= b: b >= a",
"a <= b: a <= c; c <= b",
"a <= b: a <= c; c == b",
"a <= b: a == c; c <= b",
"a >= b: b <= a",
"a < (b + c): a < c; 0 <= b",
"a < (b + c): a < (b0 + c0); b0 <= b; c0 <= c",
"a <= (a + b): 0 <= b",
"(a + b) <= c: a <= (c - b)",
}
func main() {
if err := main1(); err != nil {
os.Stderr.WriteString(err.Error() + "\n")
os.Exit(1)
}
}
func main1() error {
out.WriteString(header)
for _, reason := range reasons {
nextTmp = 0
names = map[string]bool{}
if err := gen(reason); err != nil {
return err
}
}
out.WriteString(footer)
formatted, err := format.Source(out.Bytes())
if err != nil {
return err
}
return ioutil.WriteFile("data.go", formatted, 0644)
}
var (
nextTmp int
names map[string]bool
out bytes.Buffer
)
func gen(reason string) error {
fmt.Fprintf(&out, "\n{`%q`, func(q *checker, n *a.Assert) error {\n", reason)
for i := 0; i < len(reason); i++ {
b := reason[i]
if (b < 0x20) || (0x7F <= b) {
return fmt.Errorf("bad reason %q", reason)
}
}
i := strings.IndexByte(reason, ':')
if i < 0 {
return fmt.Errorf("bad reason %q", reason)
}
claim := strings.TrimSpace(reason[:i])
requirements := strings.Split(reason[i+1:], ";")
if err := genClaim(claim); err != nil {
return fmt.Errorf("bad claim %q: %v", claim, err)
}
for _, req := range requirements {
req = strings.TrimSpace(req)
if err := genReq(req); err != nil {
return fmt.Errorf("bad req %q: %v", req, err)
}
}
{
namesAsList := []string(nil)
for name := range names {
namesAsList = append(namesAsList, name)
}
sort.Strings(namesAsList)
for _, name := range namesAsList {
fmt.Fprintf(&out, "_ = x%s\n", name)
}
}
fmt.Fprintf(&out, "return nil }},\n")
return nil
}
func genClaim(claim string) error {
n, err := parse(claim)
if err != nil {
return err
}
if err := genParseBinaryOps(n, "n.Condition()"); err != nil {
return err
}
return nil
}
func genParseBinaryOps(n *node, arg string) error {
l := genName(n.lhs)
r := genName(n.rhs)
key := keys[n.op]
if key == "" {
return fmt.Errorf("bad op %q", n.op)
}
fmt.Fprintf(&out, "op, %s, %s := parseBinaryOp(%s)\n", l, r, arg)
fmt.Fprintf(&out, "if op != t.ID%s { return errFailed }\n", key)
if l[0] == 't' {
if err := genParseBinaryOps(n.lhs, l); err != nil {
return err
}
}
if r[0] == 't' {
if err := genParseBinaryOps(n.rhs, r); err != nil {
return err
}
}
return nil
}
func genName(n *node) string {
if isConstant(n.op) {
if n.op == "0" {
return "zeroExpr"
}
return "$BAD_CONSTANT"
}
if isVariable(n.op) {
names[n.op] = true
return "x" + n.op
}
nextTmp++
return fmt.Sprintf("t%d", nextTmp-1)
}
func genReq(req string) error {
n, err := parse(req)
if err != nil {
return err
}
fmt.Fprintf(&out, "// %s\n", req)
genArgValues(n)
return genProveReasonRequirement(n, "")
}
func genArgValues(n *node) {
switch {
case isVariable(n.op):
if names[n.op] {
break
}
names[n.op] = true
fmt.Fprintf(&out, "x%s := argValue(q.tm, n.Args(), %q)\n", n.op, n.op)
fmt.Fprintf(&out, "if x%s == nil { return errFailed }\n", n.op)
case isOp(n.op):
genArgValues(n.lhs)
genArgValues(n.rhs)
}
}
func genProveReasonRequirement(n *node, name string) error {
l := genName(n.lhs)
r := genName(n.rhs)
key := keys[n.op]
if key == "" {
return fmt.Errorf("bad op %q", n.op)
}
if l[0] == 't' {
if err := genProveReasonRequirement(n.lhs, l); err != nil {
return err
}
}
if r[0] == 't' {
if err := genProveReasonRequirement(n.rhs, r); err != nil {
return err
}
}
if name == "" {
fmt.Fprintf(&out, "if err := proveReasonRequirement(q, t.ID%s, %s, %s); err != nil { return err }\n",
key, l, r)
} else {
fmt.Fprintf(&out, "%s := a.NewExpr(0, t.ID%s, 0, 0, %s.AsNode(), nil, %s.AsNode(), nil)\n",
name, key, l, r)
}
return nil
}
func parse(s string) (*node, error) {
n, s, err := parseExpr(s)
if err != nil {
return nil, err
}
if s != "" {
return nil, fmt.Errorf("parse error")
}
return n, nil
}
func parseExpr(s string) (*node, string, error) {
lhs, s, err := parseOperand(s)
if err != nil {
return nil, "", err
}
s = trim(s)
if !isOp(s) {
return nil, "", fmt.Errorf("parseExpr error")
}
i := 1
for ; i < len(s) && isOpByte(s[i]); i++ {
}
op, s := s[:i], s[i:]
s = trim(s)
rhs, s, err := parseOperand(s)
if err != nil {
return nil, "", err
}
s = trim(s)
return &node{
op: op,
lhs: lhs,
rhs: rhs,
}, s, nil
}
func parseOperand(s string) (*node, string, error) {
switch {
case isConstant(s), isVariable(s):
i := 1
for ; i < len(s) && isAlphaNumByte(s[i]); i++ {
}
return &node{op: s[:i]}, s[i:], nil
case isParen(s):
n, s, err := parseExpr(s[1:])
if err != nil {
return nil, "", err
}
if len(s) > 0 && s[0] == ')' {
return n, s[1:], nil
}
}
return nil, "", fmt.Errorf("parseOperand error")
}
type node struct {
op string
lhs *node
rhs *node
}
func (n *node) String() string {
if n == nil {
return "$NIL_NODE"
}
switch {
case isConstant(n.op), isVariable(n.op):
return n.op
case isOp(n.op):
return fmt.Sprintf("(%s %v %v)", n.op, n.lhs, n.rhs)
}
return "$BAD_NODE"
}
func isConstant(s string) bool { return s != "" && '0' <= s[0] && s[0] <= '9' }
func isOp(s string) bool { return s != "" && isOpByte(s[0]) }
func isParen(s string) bool { return s != "" && '(' == s[0] }
func isVariable(s string) bool { return s != "" && 'a' <= s[0] && s[0] <= 'z' }
func isOpByte(b byte) bool { return ('<' <= b && b <= '>') || '+' == b || '-' == b || '!' == b }
func isAlphaNumByte(b byte) bool { return ('0' <= b && b <= '9') || ('a' <= b && b <= 'z') }
func trim(s string) string {
for ; len(s) > 0 && s[0] == ' '; s = s[1:] {
}
return s
}
var keys = map[string]string{
"+": "XBinaryPlus",
"-": "XBinaryMinus",
"!=": "XBinaryNotEq",
"<": "XBinaryLessThan",
"<=": "XBinaryLessEq",
"==": "XBinaryEqEq",
">=": "XBinaryGreaterEq",
">": "XBinaryGreaterThan",
}
const header = `// Code generated by running "go generate". DO NOT EDIT.
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package check
import (
a "github.com/google/wuffs/lang/ast"
t "github.com/google/wuffs/lang/token"
)
var reasons = [...]struct {
s string
r reason
}{
`
const footer = "}\n"