termwiz: micro-optimize grapheme_column_width

While profiling `time cat bigfile` I noted that a big chunk of the
time is spent computing widths, so I wanted to dig into a bit.

After playing around with a few options, I settled on the approach
in this commit.

The key observations:

* WcWidth::from_char performs a series of binary searches.
  The fast path was for ASCII, but anything outside that range
  suffered in terms of latency.
* Binary search does a lot more work than a simple table lookup,
  so it is desirable to use a lookup, and moreso to combine the
  different tables into a single table so that classification
  is an O(1) super fast lookup in the most common cases.

Here's some benchmarking results comparing the prior implementation
(grapheme_column_width) against this new pre-computed table
implementation (grapheme_column_width_tbl).

The ASCII case is more than 5x faster than before at a reasonably snappy
~3.5ns, with the more complex cases being closer to a constant ~20ns
down from 120ns in some cases.

There are changes here to widechar_width.rs that should get
upstreamed.

```
column_width ASCII/grapheme_column_width
                        time:   [23.413 ns 23.432 ns 23.451 ns]
column_width ASCII/grapheme_column_width_tbl
                        time:   [3.4066 ns 3.4092 ns 3.4121 ns]

column_width variation selector/grapheme_column_width
                        time:   [119.99 ns 120.13 ns 120.28 ns]
column_width variation selector/grapheme_column_width_tbl
                        time:   [21.185 ns 21.253 ns 21.346 ns]

column_width variation selector unicode 14/grapheme_column_width
                        time:   [119.44 ns 119.56 ns 119.69 ns]
column_width variation selector unicode 14/grapheme_column_width_tbl
                        time:   [21.214 ns 21.236 ns 21.264 ns]

column_width WidenedIn9/grapheme_column_width
                        time:   [99.652 ns 99.905 ns 100.18 ns]
column_width WidenedIn9/grapheme_column_width_tbl
                        time:   [21.394 ns 21.419 ns 21.446 ns]

column_width Unassigned/grapheme_column_width
                        time:   [82.767 ns 82.843 ns 82.926 ns]
column_width Unassigned/grapheme_column_width_tbl
                        time:   [24.230 ns 24.319 ns 24.428 ns]
```

Here's the benchmark summary after cleaning this diff up ready
to commit; it shows ~70-80% improvement in these cases:

```
; cargo criterion -- column_width
column_width ASCII/grapheme_column_width
                        time:   [3.4237 ns 3.4347 ns 3.4463 ns]
                        change: [-85.401% -85.353% -85.302%] (p = 0.00 < 0.05)
                        Performance has improved.

column_width variation selector/grapheme_column_width
                        time:   [20.918 ns 20.935 ns 20.957 ns]
                        change: [-82.562% -82.384% -82.152%] (p = 0.00 < 0.05)
                        Performance has improved.

column_width variation selector unicode 14/grapheme_column_width
                        time:   [21.190 ns 21.210 ns 21.233 ns]
                        change: [-82.294% -82.261% -82.224%] (p = 0.00 < 0.05)
                        Performance has improved.

column_width WidenedIn9/grapheme_column_width
                        time:   [21.603 ns 21.630 ns 21.662 ns]
                        change: [-78.429% -78.375% -78.322%] (p = 0.00 < 0.05)
                        Performance has improved.

column_width Unassigned/grapheme_column_width
                        time:   [23.283 ns 23.355 ns 23.435 ns]
                        change: [-71.826% -71.734% -71.641%] (p = 0.00 < 0.05)
                        Performance has improved.
```
This commit is contained in:
Wez Furlong committed 2022-07-22 19:21:43 -07:00
1 parent 354f3577b3
commit 308bbc9038
4 files changed
+250 -50

No files matched your search

+91 -13
View File
@@ -1,22 +1,100 @@
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use termwiz::cell::grapheme_column_width;
use termwiz::cell::{grapheme_column_width, UnicodeVersion};
include!("../src/widechar_width.rs");
pub fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("grapheme_column_width a", |b| {
b.iter(|| grapheme_column_width(black_box("a"), None))
});
let table = WcLookupTable::new();
c.bench_function("grapheme_column_width emoji with variation selector", |b| {
b.iter(|| grapheme_column_width(black_box("\u{00a9}\u{FE0F}"), None))
});
{
let mut group = c.benchmark_group("Classify ASCII");
group.bench_function("WcWidth", |b| b.iter(|| WcWidth::from_char(black_box('a'))));
group.bench_function("WcLookupTable", |b| {
b.iter(|| table.classify(black_box('a')))
});
group.finish();
}
c.bench_function("grapheme_column_width WidenedIn9", |b| {
b.iter(|| grapheme_column_width(black_box("\u{231a}"), None))
});
{
let mut group = c.benchmark_group("Classify DoubleWidth");
c.bench_function("grapheme_column_width Unassigned", |b| {
b.iter(|| grapheme_column_width(black_box("\u{fbc9}"), None))
});
group.bench_function("WcWidth", |b| {
b.iter(|| WcWidth::from_char(black_box('\u{1100}')))
});
group.bench_function("WcLookupTable", |b| {
b.iter(|| table.classify(black_box('\u{1100}')))
});
group.finish();
}
{
let mut group = c.benchmark_group("Classify WidenedIn9");
group.bench_function("WcWidth", |b| {
b.iter(|| WcWidth::from_char(black_box('\u{231a}')))
});
group.bench_function("WcLookupTable", |b| {
b.iter(|| table.classify(black_box('\u{231a}')))
});
group.finish();
}
{
let mut group = c.benchmark_group("Classify Unassigned");
group.bench_function("WcWidth", |b| {
b.iter(|| WcWidth::from_char(black_box('\u{fbc9}')))
});
group.bench_function("WcLookupTable", |b| {
b.iter(|| table.classify(black_box('\u{fbc9}')))
});
group.finish();
}
{
let mut group = c.benchmark_group("column_width ASCII");
group.bench_function("grapheme_column_width", |b| {
b.iter(|| grapheme_column_width(black_box("a"), None))
});
group.finish();
}
{
let mut group = c.benchmark_group("column_width variation selector");
group.bench_function("grapheme_column_width", |b| {
b.iter(|| grapheme_column_width(black_box("\u{00a9}\u{FE0F}"), None))
});
group.finish();
}
{
let mut group = c.benchmark_group("column_width variation selector unicode 14");
let version = UnicodeVersion {
version: 14,
ambiguous_are_wide: false,
};
group.bench_function("grapheme_column_width", |b| {
b.iter(|| grapheme_column_width(black_box("\u{00a9}\u{FE0F}"), Some(version)))
});
group.finish();
}
{
let mut group = c.benchmark_group("column_width WidenedIn9");
group.bench_function("grapheme_column_width", |b| {
b.iter(|| grapheme_column_width(black_box("\u{231a}"), None))
});
group.finish();
}
{
let mut group = c.benchmark_group("column_width Unassigned");
group.bench_function("grapheme_column_width", |b| {
b.iter(|| grapheme_column_width(black_box("\u{fbc9}"), None))
});
group.finish();
}
}
criterion_group!(benches, criterion_benchmark);
+8 -3
View File
@@ -1,11 +1,19 @@
const VARIATION_SEQUENCES: &str = include_str!("../../data/emoji-variation-sequences.txt");
include!("../../src/emoji_presentation.rs");
include!("../../src/widechar_width.rs");
/// Parses emoji-variation-sequences.txt, which is part of the UCD download
/// for a given version of the Unicode spec.
/// It defines which sequences can have explicit presentation selectors.
fn main() {
println!("//! This file was generated by running:");
println!("//! cd ../codegen ; cargo run > ../emoji_variation.rs");
println!();
emit_variation_map();
}
fn emit_variation_map() {
let mut map = phf_codegen::Map::new();
'next_line: for line in VARIATION_SEQUENCES.lines() {
@@ -46,9 +54,6 @@ fn main() {
}
}
println!("//! This file was generated by running:");
println!("//! cd ../codegen ; cargo run > ../emoji_variation.rs");
println!();
println!("use crate::emoji::Presentation;");
println!();
println!(
+65 -34
View File
@@ -3,7 +3,7 @@ use crate::color::{ColorAttribute, PaletteIndex};
pub use crate::emoji::Presentation;
pub use crate::escape::osc::Hyperlink;
use crate::image::ImageCell;
use crate::widechar_width::WcWidth;
use crate::widechar_width::{WcLookupTable, WcWidth};
#[cfg(feature = "use_serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::mem;
@@ -850,6 +850,27 @@ impl UnicodeVersion {
ambiguous_are_wide: false,
}
}
#[inline]
fn width(&self, c: WcWidth) -> usize {
// Special case for symbol fonts that are naughtly and use
// the unassigned range instead of the private use range.
// <https://github.com/wez/wezterm/issues/1864>
if c == WcWidth::Unassigned {
1
} else if c == WcWidth::Ambiguous && self.ambiguous_are_wide {
2
} else if self.version >= 9 {
c.width_unicode_9_or_later() as usize
} else {
c.width_unicode_8_or_earlier() as usize
}
}
#[inline]
pub fn idx(&self) -> usize {
(if self.version > 9 { 2 } else { 0 }) | (if self.ambiguous_are_wide { 1 } else { 0 })
}
}
pub const LATEST_UNICODE_VERSION: UnicodeVersion = UnicodeVersion {
@@ -868,6 +889,10 @@ pub fn unicode_column_width(s: &str, version: Option<UnicodeVersion>) -> usize {
.sum()
}
lazy_static::lazy_static! {
static ref WCWIDTH_TABLE: WcLookupTable = WcLookupTable::new();
}
/// Returns the number of cells visually occupied by a grapheme.
/// The input string must be a single grapheme.
///
@@ -899,41 +924,47 @@ pub fn unicode_column_width(s: &str, version: Option<UnicodeVersion>) -> usize {
/// the Cell that is used to hold a grapheme, and that per-Cell version
/// can then be used to calculate width.
pub fn grapheme_column_width(s: &str, version: Option<UnicodeVersion>) -> usize {
let version = version.unwrap_or(LATEST_UNICODE_VERSION);
let ambiguous_are_wide = version.ambiguous_are_wide;
let version = version.version;
let version = version.as_ref().unwrap_or(&LATEST_UNICODE_VERSION);
let width: usize = s
.chars()
.map(|c| {
let c = WcWidth::from_char(c);
// Special case for symbol fonts that are naughtly and use
// the unassigned range instead of the private use range.
// <https://github.com/wez/wezterm/issues/1864>
if c == WcWidth::Unassigned {
1
} else if c == WcWidth::Ambiguous && ambiguous_are_wide {
2
} else if version >= 9 {
c.width_unicode_9_or_later()
} else {
c.width_unicode_8_or_earlier()
}
})
.sum::<u8>()
.into();
if version >= 14 {
match Presentation::for_grapheme(s) {
(_, Some(Presentation::Emoji)) => 2,
(_, Some(Presentation::Text)) => 1,
(Presentation::Emoji, None) => 2,
(Presentation::Text, None) => width.min(2),
}
} else {
width.min(2)
// Optimization: if there is a single byte we can directly cast
// that byte as a char which will be in the range 0.255.
// This takes ~1.5ns, and we can then look that up in the table
// which is valid for chars in the range 0-0xffff.
// That lookup also takes ~1.5ns, giving us a hot path latency
// of ~3-4ns for a grapheme string that is comprised of a single
// ASCII byte.
//
// Since we know this is a single ASCII char, we know that it
// cannot be a sequence with a variation selector, so we don't
// need to requested `Presentation` for it.
if s.len() == 1 {
let c = WCWIDTH_TABLE.classify(s.as_bytes()[0] as char);
return version.width(c);
}
// Slow path: `s.chars()` will dominate and pull up the minimum
// runtime to ~20ns
if version.version >= 14 {
// Lookup the grapheme to see if the presentation of
// the grapheme forces the width. We can bypass
// the WcWidth classification if that is true.
match Presentation::for_grapheme(s) {
(_, Some(Presentation::Emoji)) => return 2,
(_, Some(Presentation::Text)) => return 1,
(Presentation::Emoji, None) => return 2,
(Presentation::Text, None) => {}
}
}
// Otherwise, classify and sum up
let mut width = 0;
for c in s.chars() {
let c = WCWIDTH_TABLE.classify(c);
width += version.width(c);
}
width.min(2)
}
/// Models a change in the attributes of a cell in a stream of changes.
+86
View File
@@ -11,6 +11,7 @@
type R = (u32, u32);
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum WcWidth {
/// The character is single-width
One,
@@ -1492,6 +1493,7 @@ impl WcWidth {
}
/// Returns width for applications that are using unicode 8 or earlier
#[inline]
pub fn width_unicode_8_or_earlier(self) -> u8 {
match self {
Self::One => 1,
@@ -1503,6 +1505,7 @@ impl WcWidth {
}
/// Returns width for applications that are using unicode 9 or later
#[inline]
pub fn width_unicode_9_or_later(self) -> u8 {
if self == Self::WidenedIn9 {
return 2;
@@ -1511,6 +1514,89 @@ impl WcWidth {
}
}
/// An alternative interface that precomputes the values for the first 64k
/// codepoints and maintains a table that is 64kb in size.
/// Lookups are then a simple O(1) index operation that takes ~1.5ns
/// constant time for codepoints in that range, falling back to
/// the regular WcWidth::from_char for codepoints outside that range
/// (which takes 20-75ns depending on the codepoint and which table
/// it is resolved to)
pub struct WcLookupTable {
pub table: [WcWidth; 65536],
}
impl WcLookupTable {
pub fn new() -> Self {
let mut table = [WcWidth::One; 65536];
// Populate the table with data from the other tables in
// the reverse order to that used to lookup in
// WcWidth::from_char so that the precedence is the
// same in the event that there are any overlaps.
for &(start, end) in WIDENED_TABLE {
for i in start..=end.min(0xffff) {
table[i as usize] = WcWidth::WidenedIn9;
}
}
for &(start, end) in UNASSIGNED_TABLE {
for i in start..=end.min(0xffff) {
table[i as usize] = WcWidth::Unassigned;
}
}
for &(start, end) in AMBIGUOUS_TABLE {
for i in start..=end.min(0xffff) {
table[i as usize] = WcWidth::Ambiguous;
}
}
for &(start, end) in DOUBLEWIDE_TABLE {
for i in start..=end.min(0xffff) {
table[i as usize] = WcWidth::Two;
}
}
for &(start, end) in COMBININGLETTERS_TABLE {
for i in start..=end.min(0xffff) {
table[i as usize] = WcWidth::Combining;
}
}
for &(start, end) in COMBINING_TABLE {
for i in start..=end.min(0xffff) {
table[i as usize] = WcWidth::Combining;
}
}
for &(start, end) in NONCHAR_TABLE {
for i in start..=end.min(0xffff) {
table[i as usize] = WcWidth::NonCharacter;
}
}
for &(start, end) in NONPRINT_TABLE {
for i in start..=end.min(0xffff) {
table[i as usize] = WcWidth::NonPrint;
}
}
for &(start, end) in PRIVATE_TABLE {
for i in start..=end.min(0xffff) {
table[i as usize] = WcWidth::PrivateUse;
}
}
/* Implicit, as we initialized to One
for &(start, end) in ASCII_TABLE {
for i in start..=end.min(0xffff) {
table[i as usize] = WcWidth::One;
}
}
*/
Self { table }
}
/// Classify a char as a WcWidth
pub fn classify(&self, c: char) -> WcWidth {
let c32 = c as u32;
if c32 <= 0xffff {
return self.table[c32 as usize];
}
WcWidth::from_char(c)
}
}
#[cfg(test)]
mod test {
use super::*;