我目前正在尝试为我的图书馆创建高度优化,可重复使用的功能.例如,我通过以下方式编写函数"is power of 2":
template<class IntType>
inline bool is_power_of_two( const IntType x )
{
return (x != 0) && ((x & (x - 1)) == 0);
}
Run Code Online (Sandbox Code Playgroud)
这是一个可移植,低维护的实现,作为内联C++模板.此代码由VC++ 2008编译为具有分支的以下代码:
is_power_of_two PROC
test rcx, rcx
je SHORT $LN3@is_power_o
lea rax, QWORD PTR [rcx-1]
test rax, rcx
jne SHORT $LN3@is_power_o
mov al, 1
ret 0
$LN3@is_power_o:
xor al, al
ret 0
is_power_of_two ENDP
Run Code Online (Sandbox Code Playgroud)
我从这里找到了实现:"bit twiddler",它将在x64的程序集中编码,如下所示:
is_power_of_two_fast PROC
test rcx, rcx
je SHORT NotAPowerOfTwo
lea rax, [rcx-1]
and rax, …Run Code Online (Sandbox Code Playgroud) 给定一个包含N个元素的数组,我正在寻找M(M <N)个连续的子阵列,这些子阵列的长度相等或长度大多相差1个.例如,如果N = 12且M = 4,则所有子阵列都会具有相等的N/M = 3的长度.如果N = 100且M = 12,我期望长度为8和9的子阵列,并且两个尺寸应该在原始阵列内均匀分布.这项简单的任务变得有点微妙.我想出了Bresenham的线算法的改编版,当用C++编码时,它看起来像这样:
/// The function suggests how an array with num_data-items can be
/// subdivided into successively arranged groups (intervals) with
/// equal or "similar" length. The number of intervals is specified
/// by the parameter num_intervals. The result is stored into an array
/// with (num_data + 1) items, each of which indicates the start-index of
/// an interval, the last additional index being a sentinel item …Run Code Online (Sandbox Code Playgroud)