我有一些非常简单的C ++代码,可以肯定的是,使用多线程可以更快地运行3倍,但是以某种方式在Windows 10上的GCC和MSVC上只能运行3%(或更少)。
有没有互斥锁并没有共享资源。而且我看不到错误的共享或缓存颠簸如何发挥作用,因为每个线程仅修改数组的不同部分,该部分的int值超过十亿。我意识到类似这样的问题很多,但我还没有发现任何似乎可以解决这个特殊谜团的问题。
一个提示可能是,在多线程与单线程(〜885ms与〜2650ms)相比,将数组初始化移入add()函数循环确实使函数快了3倍。
请注意,只有该add()功能才被计时,在我的机器上大约需要600毫秒。我的机器有4个超线程内核,因此我正在将代码threadCount设置为8,然后设置为1。
知道会发生什么吗?有没有办法(适当时)关闭处理器中的功能,这些功能会导致诸如错误共享(可能就像我们在此处看到的那样)之类的事情发生?
#include <chrono>
#include <iostream>
#include <thread>
void startTimer();
void stopTimer();
void add(int* x, int* y, int threadIdx);
namespace ch = std::chrono;
auto start = ch::steady_clock::now();
const int threadCount = 8;
int itemCount = 1u << 30u; // ~1B items
int itemsPerThread = itemCount / threadCount;
int main() {
int* x = new int[itemCount];
int* y = new …Run Code Online (Sandbox Code Playgroud)