...
Run Format

Source file src/runtime/fastlog2.go

     1	// Copyright 2015 The Go Authors. All rights reserved.
     2	// Use of this source code is governed by a BSD-style
     3	// license that can be found in the LICENSE file.
     4	
     5	package runtime
     6	
     7	import "unsafe"
     8	
     9	// fastlog2 implements a fast approximation to the base 2 log of a
    10	// float64. This is used to compute a geometric distribution for heap
    11	// sampling, without introducing dependencies into package math. This
    12	// uses a very rough approximation using the float64 exponent and the
    13	// first 25 bits of the mantissa. The top 5 bits of the mantissa are
    14	// used to load limits from a table of constants and the rest are used
    15	// to scale linearly between them.
    16	func fastlog2(x float64) float64 {
    17		const fastlogScaleBits = 20
    18		const fastlogScaleRatio = 1.0 / (1 << fastlogScaleBits)
    19	
    20		xBits := float64bits(x)
    21		// Extract the exponent from the IEEE float64, and index a constant
    22		// table with the first 10 bits from the mantissa.
    23		xExp := int64((xBits>>52)&0x7FF) - 1023
    24		xManIndex := (xBits >> (52 - fastlogNumBits)) % (1 << fastlogNumBits)
    25		xManScale := (xBits >> (52 - fastlogNumBits - fastlogScaleBits)) % (1 << fastlogScaleBits)
    26	
    27		low, high := fastlog2Table[xManIndex], fastlog2Table[xManIndex+1]
    28		return float64(xExp) + low + (high-low)*float64(xManScale)*fastlogScaleRatio
    29	}
    30	
    31	// float64bits returns the IEEE 754 binary representation of f.
    32	// Taken from math.Float64bits to avoid dependencies into package math.
    33	func float64bits(f float64) uint64 { return *(*uint64)(unsafe.Pointer(&f)) }
    34	

View as plain text