一个伟大的编程资源,Bit Twiddling Hacks,提出(这里)以下方法来计算32位整数的log2:
#define LT(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n
static const char LogTable256[256] =
{
-1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
LT(4), LT(5), LT(5), LT(6), LT(6), LT(6), LT(6),
LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7)
};
unsigned int v; // 32-bit word to find the log of
unsigned r; // r will be lg(v)
register …
Run Code Online (Sandbox Code Playgroud) 所有代码都在linux上的同一台机器上运行.
在python中:
import numpy as np
drr = abs(np.random.randn(100000,50))
%timeit np.log2(drr)
Run Code Online (Sandbox Code Playgroud)
10个循环,最佳3:每循环77.9 ms
在C++中(使用g ++ -o log ./log.cpp -std = c ++ 11 -O3编译):
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
#include <ctime>
int main()
{
std::mt19937 e2(0);
std::normal_distribution<> dist(0, 1);
const int n_seq = 100000;
const int l_seq = 50;
static double x[n_seq][l_seq];
for (int n = 0;n < n_seq; ++n) {
for (int k = 0; k < l_seq; ++k) {
x[n][k] = abs(dist(e2));
if(x[n][k] …
Run Code Online (Sandbox Code Playgroud)