{"id":106321,"date":"2022-03-08T07:00:00","date_gmt":"2022-03-08T15:00:00","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/oldnewthing\/?p=106321"},"modified":"2022-03-08T10:41:15","modified_gmt":"2022-03-08T18:41:15","slug":"20220308-00","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/oldnewthing\/20220308-00\/?p=106321\/","title":{"rendered":"Optimizing code to darken a bitmap, part 2"},"content":{"rendered":"<p>Our investigation into a simple function to darken a bitmap left off with this function:<\/p>\n<pre>struct Pixel\r\n{\r\n    uint8_t c[4]; \/\/ four channels: red, green, blue, alpha\r\n    uint32_t v;   \/\/ full pixel value as a 32-bit integer\r\n};\r\n\r\nvoid darken(Pixel* first, Pixel* last, int darkness)\r\n{\r\n  int lightness = 256 - darkness;\r\n  for (; first &lt; last; ++first) {\r\n    first-&gt;c[0] = (uint8_t)(first-&gt;c[0] * lightness \/ 256);\r\n    first-&gt;c[1] = (uint8_t)(first-&gt;c[1] * lightness \/ 256);\r\n    first-&gt;c[2] = (uint8_t)(first-&gt;c[2] * lightness \/ 256);\r\n  }\r\n}\r\n<\/pre>\n<p>There&#8217;s a lot of multiplication going on here, and multiplication tends to be one of the more expensive CPU instructions. Maybe we can collapse them into a single multiplication operation by running the calculations in parallel.<\/p>\n<p>The idea here is to break the 32-bit integer into the respective channels, but spread them out so they act like independent lanes of a SIMD register. (This technique goes by the name <a href=\"https:\/\/en.wikipedia.org\/wiki\/SWAR\"> SWAR<\/a>, short for &#8220;SIMD within a register&#8221;.) Once they&#8217;ve been spread out into lanes, we perform a single multiplication, which acts like a parallel multiplication across all the lanes, thanks to the magic of the distributive law:<\/p>\n<p>(100\u00b2<var>a<\/var> + 100<var>b<\/var> + 100<var>c<\/var>)<var>d<\/var> = 100\u00b2<var>a<\/var><var>d<\/var> + 100<var>b<\/var><var>d<\/var> + <var>c<\/var><var>d<\/var><\/p>\n<p>If <var>c<\/var><var>d<\/var> &lt; 100, then there will be no carry into the hundreds place, and similar, if <var>b<\/var><var>d<\/var> &lt; 100, then there will be no carry into the ten thousands place. Under such conditions, you can pluck out the individual products by extracting the corresponding pairs of digits from the final product.<\/p>\n<p>It so happens that my program uses only three darkness values: 8, 16, and 24, corresponding to lightness factors 248, 240, and 232, respectively. The application of the lightness factor can therefore be simplified to<\/p>\n<pre>newPixel = oldPixel * (lightness \/ 8) \/ 32;\r\n<\/pre>\n<p>which can be rewritten as<\/p>\n<pre>newPixel = oldPixel - ceil(oldPixel * (darkness \/ 8) \/ 32);\r\n<\/pre>\n<p>The truncation toward zero in the lightness calculation becomes a ceiling calculation when viewed as darkness.<\/p>\n<p>Reinterpreting it as a darkness calculation is helpful because the value of <code>darkness \/ 8<\/code> is limited to the values 1, 2, and 3. The factor is at most two bits.<\/p>\n<p>Multiplying an 8-bit value with a 2-bit value produces a 10-bit result. And we can squeeze three 10-bit fields inside a 32-bit integer.<\/p>\n<p>A quick mental check confirms that rounding up any fractional portion won&#8217;t take us into 11 bits:<\/p>\n<p>255 \u00d7 3 &lt; 256 \u00d7 3 = 256 \u00d7 4 \u2212 256 &lt; 256 \u00d7 4 \u2212 32 = 10\u00b9\u00b9 \u2212 32.<\/p>\n<p>The idea therefore is that we take our three channel values and arrange them inside a 32-bit integer like this:<\/p>\n<table class=\"cp3\" style=\"border-collapse: collapse;\" border=\"0\" cellspacing=\"0\" cellpadding=\"3\">\n<tbody>\n<tr style=\"font-size: 50%; text-align: center;\">\n<td>3<br \/>\n1<\/td>\n<td>3<br \/>\n0<\/td>\n<td>2<br \/>\n9<\/td>\n<td>2<br \/>\n8<\/td>\n<td>2<br \/>\n7<\/td>\n<td>2<br \/>\n6<\/td>\n<td>2<br \/>\n5<\/td>\n<td>2<br \/>\n4<\/td>\n<td>2<br \/>\n3<\/td>\n<td>2<br \/>\n2<\/td>\n<td>2<br \/>\n1<\/td>\n<td>2<br \/>\n0<\/td>\n<td>1<br \/>\n9<\/td>\n<td>1<br \/>\n8<\/td>\n<td>1<br \/>\n7<\/td>\n<td>1<br \/>\n6<\/td>\n<td>1<br \/>\n5<\/td>\n<td>1<br \/>\n4<\/td>\n<td>1<br \/>\n3<\/td>\n<td>1<br \/>\n2<\/td>\n<td>1<br \/>\n1<\/td>\n<td>1<br \/>\n0<\/td>\n<td>\n9<\/td>\n<td>\n8<\/td>\n<td>\n7<\/td>\n<td>\n6<\/td>\n<td>\n5<\/td>\n<td>\n4<\/td>\n<td>\n3<\/td>\n<td>\n2<\/td>\n<td>\n1<\/td>\n<td>\n0<\/td>\n<\/tr>\n<tr style=\"text-align: right;\">\n<td style=\"border: solid 1px black; width: 2ex;\" colspan=\"2\">\u00a0<\/td>\n<td style=\"border: solid 1px black; width: 10ex;\" colspan=\"10\">b<\/td>\n<td style=\"border: solid 1px black; width: 10ex;\" colspan=\"10\">g<\/td>\n<td style=\"border: solid 1px black; width: 10ex;\" colspan=\"10\">r<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>In other words,<\/p>\n<ul>\n<li><code>value[ 0: 9] = r;<\/code><\/li>\n<li><code>value[10:19] = g;<\/code><\/li>\n<li><code>value[20:29] = b;<\/code><\/li>\n<li><code>value[30:31]<\/code> are unused<\/li>\n<\/ul>\n<p>The lanes are 10 bits wide, so multiplying the entire integer by 1, 2, or 3 will not trigger any carries across lanes.<\/p>\n<p>After the multiply, we reinterpret the integer as a fixed-point value, by applying an implied scale of 32 = 2\u2075. Rounding up the fixed-point value to the next integer is the same as rounding up the original integer to the next multiple of 32.<\/p>\n<p>Once the multiplication and rounding is done, we extract the integer portion of the fixed-point fields (which means we take the top five bits of each field) and subtract them from our starting value.<\/p>\n<pre>constexpr unsigned pack_fields(uint8_t r, uint8_t g, uint8_t b)\r\n{\r\n  return r | (g &lt;&lt; 10) | (b &lt;&lt; 20);\r\n}\r\n\r\nvoid darken(Pixel* first, Pixel* last, int darkness)\r\n{\r\n  int factor = darkness \/ 8;\r\n  for (; first &lt; last; ++first) {\r\n    uint32_t fields = pack_fields(\r\n        first-&gt;c[0], first-&gt;c[1], first-&gt;c[2]);\r\n    fields *= factor;\r\n    fields += pack_fields(31, 31, 31);\r\n    first-&gt;c[0] -= (fields &gt;&gt;  5) &amp; 31;\r\n    first-&gt;c[1] -= (fields &gt;&gt; 15) &amp; 31;\r\n    first-&gt;c[2] -= (fields &gt;&gt; 25) &amp; 31;\r\n  }\r\n}\r\n<\/pre>\n<p>Unfortunately, this benchmarks at 2.9\u00d7 <i>slower<\/i> than the non-parallel version.<\/p>\n<p>Okay, so maybe it&#8217;s the byte access that is killing us. Let&#8217;s load and store entire pixels at a time.<\/p>\n<pre>void darken(Pixel* first, Pixel* last, int darkness)\r\n{\r\n  int factor = darkness \/ 8;\r\n  for (; first &lt; last; ++first) {\r\n    <span style=\"color: blue;\">uint32_t v = first-&gt;v;\r\n    uint32_t fields = (v &amp; 0xFF) |\r\n                     ((v &amp; 0xFF00) &lt;&lt; 2) |\r\n                     ((v &amp; 0xFF0000) &lt;&lt; 4);<\/span>\r\n    fields *= factor;\r\n    fields += pack_fields(31, 31, 31);\r\n    <span style=\"color: blue;\">uint32_t diff = ((fields &gt;&gt; 5) &amp; 0x1F) |\r\n                    ((fields &gt;&gt; 7) &amp; 0x1F00) |\r\n                    ((fields &gt;&gt; 9) &amp; 0x1F0000) |\r\n    first-&gt;v = v - diff;<\/span>\r\n  }\r\n}\r\n<\/pre>\n<p>Still 2.1\u00d7 slower than the non-parallel version. A tiny improvement but still way behind.<\/p>\n<p>Some micro-tweaking here won&#8217;t help much: We waste our time building up the difference fields, when we can just subtract each of the pieces as we calculate them.<\/p>\n<pre>void darken(Pixel* first, Pixel* last, int darkness)\r\n{\r\n  int factor = darkness \/ 8;\r\n  for (; first &lt; last; ++first) {\r\n    uint32_t v = first-&gt;v;\r\n    uint32_t fields = (v &amp; 0xFF) |\r\n                     ((v &amp; 0xFF00) &lt;&lt; 2) |\r\n                     ((v &amp; 0xFF0000) &lt;&lt; 4);\r\n    fields *= factor;\r\n    fields += pack_fields(31, 31, 31);\r\n    <span style=\"color: blue;\">v -= (fields &gt;&gt; 5) &amp; 0x1F;\r\n    v -= (fields &gt;&gt; 7) &amp; 0x1F00;\r\n    v -= (fields &gt;&gt; 9) &amp; 0x1F0000;\r\n    first-&gt;v = v;<\/span>\r\n  }\r\n}\r\n<\/pre>\n<p>As expected, this doesn&#8217;t really help. Still 2.1\u00d7 slower than the non-parallel version.<\/p>\n<p>Part of the problem might be that I&#8217;m running the benchmarks on an x86-64 system, and the x86-64 does not have dedicated bitfield manipulation instructions, unlike other processors like PowerPC, ARM, and AArch64.<\/p>\n<p>Or maybe the problem is that I&#8217;m doing a multiply. Since I know that the darkness factor is going to be 1, 2, or 3, I can strength-reduce that to an addition. We&#8217;ll look at how to do that jumplessly next time.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Exploiting parallel arithmetic.<\/p>\n","protected":false},"author":1069,"featured_media":111744,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[25],"class_list":["post-106321","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oldnewthing","tag-code"],"acf":[],"blog_post_summary":"<p>Exploiting parallel arithmetic.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/106321","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/users\/1069"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/comments?post=106321"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/106321\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media\/111744"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media?parent=106321"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/categories?post=106321"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/tags?post=106321"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}