gpt4 book ai didi

c++ - 将 unsigned int 更改为 size_t 会影响性能吗?

转载 作者:搜寻专家 更新时间:2023-10-31 00:57:41 26 4
gpt4 key购买 nike

在我将一些遗留代码从 win32 移植到 win64 之后,在我讨论了消除警告“可能丢失数据”(What's the best strategy to get rid of "warning C4267 possible loss of data"?) 的最佳策略之后。我即将在我的代码中用 size_t 替换许多 unsigned int

但是,我的代码在性能方面很关键(我什至无法在 Debug 中运行它……太慢了)。

我做了一个快速基准测试:

#include "stdafx.h"

#include <iostream>
#include <chrono>
#include <string>

template<typename T> void testSpeed()
{
auto start = std::chrono::steady_clock::now();

T big = 0;
for ( T i = 0; i != 100000000; ++i )
big *= std::rand();

std::cout << "Elapsed " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count() << "ms" << std::endl;
}

int main()
{
testSpeed<size_t>();
testSpeed<unsigned int>();

std::string str;
std::getline( std::cin, str ); // pause

return 0;
}

针对 x64 编译,输出:

Elapsed 2185ms
Elapsed 2157ms

针对 x86 编译,输出:

Elapsed 2756ms
Elapsed 2748ms

很明显,使用 size_t 而不是 unsigned int 对性能影响不大。但情况真的总是如此吗(很难以这种方式对性能进行基准测试)。

unsigned int 更改为 size_t 是否/可能会影响 CPU 性能(现在将操作 64 位对象而不是 32 位对象)?

最佳答案

绝对不是。在现代(甚至更老的)CPU 上,64 位整数运算的执行速度与 32 位运算一样快。

在我的 i7 4600u 上进行算术运算的示例 a * b/c :

(int32_t) * (int32_t)/(int32_t):1.3 纳秒
(int64_t) * (int64_t)/(int64_t):1.3 纳秒

两个测试都针对 x64 目标编译(与您的目标相同)。

但是,如果您的代码管理充满整数的大型对象(大型整数数组,fox 示例),使用 size_t 而不是 unsigned int 可能会对性能产生影响如果缓存未命中计数增加(更大的数据可能会超过缓存容量)。检查对性能影响的最可靠方法是在这两种情况下测试您的应用程序。使用您自己的类型定义为 size_tunsigned int 然后对您的应用程序进行基准测试。

关于c++ - 将 unsigned int 更改为 size_t 会影响性能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37004461/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com