小编nam*_*ame的帖子

评估 sizeof 导致性能改进 C

我有一个动态数组,并且有一个热循环,它花费大量时间向我实现的动态数组添加大量元素。

动态数组的工作原理是在值数组的开头存储一个标头:

typedef struct
{
    unsigned char* begin; // Pointer to first element (should just point to end of struct, the header is stored prior data)
    unsigned char* end; // Pointer to last element
    size_t typeSize; // Size of type that the array stores
    size_t capacity; // capacity of array (when size ((end - begin) / typeSize) exceeds capacity, realloc)
} dynamicArr;
Run Code Online (Sandbox Code Playgroud)

出于某种原因,当我将 与sizeof item进行比较时,循环运行得更快,而当我不进行比较时typeSize,它的幅度很大(增加了 30%)。

请注意,比较只是为了防止添加不同类型的项目并导致数组中的未对齐。如果正确使用动态数组来存储 1 种类型,则无论如何都不会发生这种情况,因此在实践中应始终评估为真。

这是将元素添加到列表的代码:

if (arr)
{
    dynamicArr* header = …
Run Code Online (Sandbox Code Playgroud)

c optimization x86-64 compiler-optimization

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

使用 T[] 访问彼此相邻声明的两个 T 类型对象是否是未定义的行为?

我最近观看了 Miro Kenjp 关于“不符合标准的 C++:委员会向你隐藏的秘密”的 CppCon 演讲。

在 28:30 ( https://youtu.be/IAdLwUXRUvg?t=1710 ) 他说访问彼此相邻的双打是 UB,我不太明白为什么。有人可以解释为什么会这样吗?

如果是这种情况,那么它的 UB 肯定会以这种方式访问​​其他东西,例如:

int* twoInts = malloc(sizeof(int) * 2);
int secondInt = twoInts[1]; //Undefined behaviour?
Run Code Online (Sandbox Code Playgroud)

c++ language-lawyer

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

随机数生成器性能因平台而异

我正在 C++ 中测试随机数生成器的性能,并得到了一些我不明白的非常奇怪的结果。

我已经测试了 std::rand 与使用 std::minstd_rand 的 std::uniform_real_distribution 。

计时 std::rand 代码

auto start = std::chrono::high_resolution_clock::now();

for (int i = 0; i < 1000000; ++i)
    std::rand();

auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
std::cout << "Elapsed time: " << elapsed.count() * 1000 << " ms\n";
Run Code Online (Sandbox Code Playgroud)

使用 std:minstd_rand 计时 std::uniform_real_distribution 的代码

std::minstd_rand Mt(std::chrono::system_clock::now().time_since_epoch().count());
std::uniform_real_distribution<float> Distribution(0, 1);

auto start = std::chrono::high_resolution_clock::now();

for (int i = 0; i < 1000000; ++i)
    Distribution(Mt);

auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = …
Run Code Online (Sandbox Code Playgroud)

c++ random performance c++17

2
推荐指数
1
解决办法
282
查看次数