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

jpo*_*o38 4 c++ performance

在我将一些遗留代码从 win32 移植到 win64 之后,在我讨论了消除“可能丢失数据”警告的最佳策略是什么之后(摆脱“警告 C4267 可能丢失数据”的最佳策略是什么?)。我即将取代许多unsigned int通过size_t在我的代码。

但是,我的代码在性能方面至关重要(我什至无法在调试中运行它......太慢了)。

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

为 x64 编译,它输出:

Elapsed 2185ms
Elapsed 2157ms
Run Code Online (Sandbox Code Playgroud)

为 x86 编译,它输出:

Elapsed 2756ms
Elapsed 2748ms
Run Code Online (Sandbox Code Playgroud)

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

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

shr*_*ike 6

当然不。在现代(甚至更老)的 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可能会对性能产生影响。检查对性能的影响的最可靠方法是在两种情况下测试您的应用程序。用你自己的类型Typedef的要么size_t还是unsigned int那么基准您的应用程序。