我正在使用增强spsc_queue
将我的东西从一个线程移动到另一个线程。这是我的软件中的关键位置之一,所以我想尽快完成它。我写了这个测试程序:
#include <boost/lockfree/spsc_queue.hpp>
#include <stdint.h>
#include <condition_variable>
#include <thread>
const int N_TESTS = 1000;
int results[N_TESTS];
boost::lockfree::spsc_queue<int64_t, boost::lockfree::capacity<1024>> testQueue;
using std::chrono::nanoseconds;
using std::chrono::duration_cast;
int totalQueueNano(0);
int totalQueueCount(0);
void Consumer() {
int i = 0;
int64_t scheduledAt;
while (i < N_TESTS - 1) {
while (testQueue.pop(scheduledAt)) {
int64_t dequeuedAt = (duration_cast<nanoseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch())).count();
auto diff = dequeuedAt - scheduledAt;
totalQueueNano += diff;
++totalQueueCount;
results[i] = diff;
++i;
}
}
for (int i = 0; i < N_TESTS; i++) {
printf("%d ", results[i]);
}
printf("\nspsc_queue latency average nano = %d\n", totalQueueNano / totalQueueCount);
}
int main() {
std::thread t(Consumer);
usleep(1000000);
for (int i = 0; i < N_TESTS; i++) {
usleep(1000);
int64_t scheduledAt = (duration_cast<nanoseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch())).count();
testQueue.push(scheduledAt);
}
usleep(1000000);
return 0;
}
编译标志:
g++ -std=c++0x -O3 -Wall -c -fmessage-length=0 -march=native -mtune=native -pthread -MMD -MP -MF"src/TestProject.d" -MT"src/TestProject.d" -o "src/TestProject.o" "../src/TestProject.cpp"
g++ -pthread -o "TestProject" ./src/TestProject.o -lpthread
在我的机器上:RHEL 7.1、gcc 4.8.3、Xeon E5-2690 v3 我收到 290-300 纳秒。
- 我的测试应用程序有多好?我是否正确测量了“spsc_queue”延迟?
- 目前业界将数据从一个线程传递到另一个线程的最佳时间是什么?
- 使用 boost spsc_queue 将数据从一个线程移动到另一个线程是一个好的选择吗?
- 你能推荐一些比 spsc_queue 更快的东西吗?
- 你能编写一段代码来显着更快地完成相同的工作吗?
upd:需要队列机制。如果第一个线程每 1000 纳秒生成一次数据,但第二个线程花费 10 000 纳秒来处理单个项目,我需要在短时间内“排队”多个项目。但我的“队列”从来都不是“太大”。固定大小的短环形缓冲区必须足够。
upd2简而言之,问题是 - 最快的单个生产者单个消费者队列(最有可能基于固定大小的环形缓冲区)是什么?我正在使用 boost spsc_queue 并且实现了约 300 ns 的延迟,你能建议更快的东西吗?
upd3在 Java 世界中,有一种 Disruptor 可以实现 50 ns 延迟https://code.google.com/p/disruptor/wiki/PerformanceResults https://code.google.com/p/disruptor/wiki/PerformanceResults我们在 C++ 中是否有具有相同 50 ns 延迟的东西?