小编Qua*_*Cat的帖子

max(ctz(x), ctz(y)) 是否有更快的算法?

对于min(ctz(x), ctz(y)),我们可以使用ctz(x | y)来获得更好的性能。但是关于max(ctz(x), ctz(y))?

ctz表示“计数尾随零”。

C++ 版本(编译器资源管理器)

#include <algorithm>
#include <bit>
#include <cstdint>

int32_t test2(uint64_t x, uint64_t y) {
    return std::max(std::countr_zero(x), std::countr_zero(y));
}
Run Code Online (Sandbox Code Playgroud)

Rust 版本(编译器资源管理器)

pub fn test2(x: u64, y: u64) -> u32 {
    x.trailing_zeros().max(y.trailing_zeros())
}
Run Code Online (Sandbox Code Playgroud)

c++ algorithm bit-manipulation micro-optimization rust

33
推荐指数
3
解决办法
3184
查看次数

x86-64 的缓存填充大小应该为 128 字节吗?

我发现了一条来自 的评论crossbeam。

从 Intel 的 Sandy Bridge 开始,空间预取器现在一次提取成对的 64 字节缓存线,因此我们必须对齐到 128 字节而不是 64。

资料来源:

我在英特尔的手册中没有找到这样的说法。但直到最新的提交,folly仍然使用 128 字节填充,这让我很有说服力。所以我开始编写代码来看看是否可以观察到这种行为。这是我的代码。

#include <thread>

int counter[1024]{};

void update(int idx) {
    for (int j = 0; j < 100000000; j++) ++counter[idx];
}

int main() {
    std::thread t1(update, 0);
    std::thread t2(update, 1);
    std::thread t3(update, 2);
    std::thread t4(update, 3);
    t1.join();
    t2.join();
    t3.join();
    t4.join();
}
Run Code Online (Sandbox Code Playgroud)

编译器资源管理器

我的CPU是锐龙3700X。当索引为0、1、2、3时,大约需要 1.2 秒才能完成。当索引为0, 16, 32,时 …

c++ x86-64 rust cpu-cache false-sharing

15
推荐指数
1
解决办法
2210
查看次数

如何存储编译时动态分配的内存以便在运行时使用?

假设我有一个constexpr变量,其中包含所有小于 2 16的素数。

constexpr auto primes = [] {
    constexpr int N = 1 << 16;
    std::array<int, 6542> ret;
    bool not_prime[N] = {};
    int prime_cnt = 0;
    for (int i = 2; i < N; i++) {
        if (!not_prime[i]) {
            ret[prime_cnt++] = i;
            for (int j = 2 * i; j < N; j += i) not_prime[j] = true;
        }
    }
    return ret;
}();
Run Code Online (Sandbox Code Playgroud)

这里我手动指定了 的ret数组大小。当我想要更改时N,我必须重新运行此循环以查看最终prime_cnt值是什么并手动指定它。特别是,如果我增加N,我必须首先给出一个上限猜测以避免段错误。

在C++20中,我们可以在编译时动态分配内存,因此我们constexpr现在有了向量。所以我们不再需要担心上限问题。但这样的值不能在运行时使用,这意味着这段代码是无效的。 …

c++ constexpr c++20

6
推荐指数
1
解决办法
805
查看次数

如何在属性中使用字符串变量

在 GCC 和 Clang 中,我们可以将整数变量传递给属性。

constexpr auto SIZE = 16;

int a [[gnu::vector_size(SIZE)]];
Run Code Online (Sandbox Code Playgroud)

当我们编写模板时,这特别有用。

template<size_t N>
struct Vec {
    int inner [[gnu::vector_size(N)]];
};
Run Code Online (Sandbox Code Playgroud)

但是,如果该属性需要一个字符串,我找不到使用这样的变量的方法。这两种方法都不起作用。

constexpr const char* TARGET = "default";

[[gnu::target(TARGET)]] void foo() {}
Run Code Online (Sandbox Code Playgroud)
constexpr const char TARGET[] = "default";

[[gnu::target(TARGET)]] void foo() {}
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这一目标?

c++ gcc clang

5
推荐指数
1
解决办法
231
查看次数