std::inner_product比手动快4倍,但不使用SIMD
std::inner_product 4x faster than manual but no SIMD being used?
我对std::inner_product()
与手动点积计算的性能比较感兴趣,所以我做了一个测试。
std::inner_product()
比手动实现快4倍。我觉得这很奇怪,因为没有那么多方法来计算它,不是吗?我也看不到任何SSE/AVX寄存器在计算点被使用。
安装:VS2013/MSVC(12?), Haswell i7 4770 CPU, 64位编译,发布模式
下面是c++测试代码:#include <iostream>
#include <functional>
#include <numeric>
#include <cstdint>
int main() {
const int arraySize = 1000;
const int numTests = 500;
unsigned int x, y = 0;
unsigned long long* array1 = new unsigned long long[arraySize];
unsigned long long* array2 = new unsigned long long[arraySize];
//Initialise arrays
for (int i = 0; i < arraySize; i++){
unsigned long long val = __rdtsc();
array1[i] = val;
array2[i] = val;
}
//std::inner_product test
unsigned long long timingBegin1 = __rdtscp(&s);
for (int i = 0; i < numTests; i++){
volatile unsigned long long result = std::inner_product(array1, array1 + arraySize, array2, static_cast<uint64_t>(0));
}
unsigned long long timingEnd1 = __rdtscp(&s);
f, s = 0;
//Manual Dot Product test
unsigned long long timingBegin2 = __rdtscp(&f);
for (int i = 0; i < numTests; i++){
volatile unsigned long long result = 0;
for (int i = 0; i < arraySize; i++){
result += (array1[i] * array2[i]);
}
}
unsigned long long timeEnd2 = __rdtscp(&f);
std::cout << "STL: : " << static_cast<double>(finish1 - start1) / numTests << " CPU cycles per dot product" << std::endl;
std::cout << "Manually : " << static_cast<double>(finish2 - start2) / numTests << " CPU cycles per dot product" << std::endl;
您的测试很糟糕,这可能会造成很大的差异。
volatile uint64_t result = 0; for (int i = 0; i < arraySize; i++){ result += (array1[i] * array2[i]);
注意您是如何在这里连续使用volatile
限定变量的。这将强制编译器将临时结果写入内存。
相反,您的inner_product
版本:
volatile uint64_t result = std::inner_product(array1, array1 + arraySize, array2, static_cast<uint64_t>(0));
首先计算内部积,允许优化,然后才将结果分配给volatile
合格的变量。
相关文章:
- 我想知道长双倍和双倍之间的区别
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- 按值 C++ 返回时进行双倍移动
- 求和 int 乘以双倍时的欠/过近似
- 在 C++ 中使用 SIMD 向量的矩阵乘法
- 从'size_t'转换为"常量双倍",可能会丢失数据
- 二叉搜索不收敛为双倍
- 编写一个代码,使年利率翻倍
- 将一个双倍值乘以10会发生什么
- C++数组与向量排序(在我的情况下,向量比数组慢~2.5倍(无优化))
- 将非常大的 int 转换为双倍,在某些计算机上会损失精度
- 双吨级 - 从单级过渡到双倍级
- 为什么从具有较大阵列的 SIMD 内部函数中获得的相对加速比标量更大?
- 是否有用于元素部分移位的 simd 指令/内在/内置指令?
- 如何将包含指数的 QString 转换为C++中的双倍?
- 计算阶乘的 C++17 倍表达式中的错误
- 防止在字符数组中输入双倍空格在 C++
- 将uintptr_t转换为布尔值会使 SSO 基准速度减慢数倍
- std::inner_product比手动快4倍,但不使用SIMD