Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is math.bits in Go using machine code instructions?

Tags:

go

The new golang package "math/bits" provides useful functions. The source code shows how the function result are computed.

Are these functions replaced by the corresponding processor OP codes when available?

like image 309
chmike Avatar asked Sep 19 '26 22:09

chmike


2 Answers

Yes, as stated in Go 1.9 Release Notes: New bit manipulation package:

Go 1.9 includes a new package, math/bits, with optimized implementations for manipulating bits. On most architectures, functions in this package are additionally recognized by the compiler and treated as intrinsics for additional performance.

Some related / historical github issues:

math/bits: an integer bit twiddling library #18616

proposal: cmd/compile: intrinsicify user defined assembly functions #17373

Provide a builtin for population counting / hamming distance #10757

like image 158
icza Avatar answered Sep 21 '26 13:09

icza


Yes it does. You can see an example of it working here

first compile this

package main

import (
    "fmt"
    "math/bits"
)

func count(i uint) {
    fmt.Printf("%d has %d length\n", i, bits.Len(i))
}

func main() {
    for i := uint(0); i < 100; i++ {
        count(i)
    }
}

Then look at the disassembly. Note the BSR instruction - Bit Scan Reverse which from the manual: Searches the value in a register or a memory location (second operand) for the most-significant set bit.

0000000000489620 <main.count>:
  489620:       64 48 8b 0c 25 f8 ff    mov    %fs:0xfffffffffffffff8,%rcx
  489627:       ff ff 
  489629:       48 3b 61 10             cmp    0x10(%rcx),%rsp
  48962d:       0f 86 f2 00 00 00       jbe    489725 <main.count+0x105>
  489633:       48 83 ec 78             sub    $0x78,%rsp
  489637:       48 89 6c 24 70          mov    %rbp,0x70(%rsp)
  48963c:       48 8d 6c 24 70          lea    0x70(%rsp),%rbp
  489641:       48 8b 84 24 80 00 00    mov    0x80(%rsp),%rax
  489648:       00 
  489649:       48 0f bd c8             bsr    %rax,%rcx  ; **** Bit scan reverse instruction ***
  48964d:       48 89 44 24 48          mov    %rax,0x48(%rsp)
  489652:       48 c7 c0 ff ff ff ff    mov    $0xffffffffffffffff,%rax
  489659:       48 0f 44 c8             cmove  %rax,%rcx
  48965d:       48 8d 41 01             lea    0x1(%rcx),%rax
like image 32
Nick Craig-Wood Avatar answered Sep 21 '26 11:09

Nick Craig-Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!