考虑以下 C++ 代码:
#include "threadpool.hpp"
#include <chrono>
#include <list>
#include <iostream>
#include <cmath>
int loop_size;
void process(int num) {
double x = 0;
double sum = 0;
for(int i = 0; i < loop_size; ++i) {
x += 0.0001;
sum += sin(x) / cos(x) + cos(x) * cos(x);
}
}
int main(int argc, char* argv[]) {
if(argc < 3) {
std::cerr << argv[0] << " [thread_pool_size] [threads] [sleep_time]" << std::endl;
exit(0);
}
thread_pool* pool = nullptr;
int th_count = std::atoi(argv[1]);
if(th_count != 0) {
pool = new thread_pool(th_count);
}
loop_size = std::stoi(argv[3]);
int max = std::stoi(argv[2]);
auto then = std::chrono::steady_clock::now();
std::list<std::thread> ths;
if(th_count == 0) {
for(int i = 0; i < max; ++i) {
ths.emplace_back(&process, i);
}
for(std::thread& t : ths) {
t.join();
}
} else {
for(int i = 0; i < max; ++i) {
pool->enqueue(std::bind(&process, i));
}
delete pool;
}
int diff = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - then).count();
std::cerr << "Time: " << diff << '\n';
return 0;
}
"threadpool.hpp" 是 this github repo 的修改版本可用here
我在我的机器 (Corei7-6700) 和一个 88 核服务器 (2x Xeon E5-2696 v4) 上编译了上面的代码。结果我无法解释。
这是我运行代码的方式:
tp <threadpool size> <number of threads> <iterations>
同样的代码在更快的机器上运行得更慢!我的本地机器上有 8 个内核,远程服务器上有 88 个内核,这些是结果:(最后两列表示每台机器上完成的平均时间(以毫秒为单位)
+============+=========+============+=============+====================+
| Threadpool | Threads | Iterations | Corei7-6700 | 2x Xeon E5-2696 v4 |
+============+=========+============+=============+====================+
| 100 | 100000 | 1000 | 1300 | 6000 |
+------------+---------+------------+-------------+--------------------+
| 1000 | 100000 | 1000 | 1400 | 5000 |
+------------+---------+------------+-------------+--------------------+
| 10000 | 100000 | 1000 | 1470 | 3400 |
+------------+---------+------------+-------------+--------------------+
似乎拥有更多内核会使代码运行速度变慢。所以我将服务器 ( taskset ) 上的 CPU 亲和性减少到 8 个内核,然后再次运行代码:
taskset 0-7 tp <threadpool size> <number of threads> <iterations>
这是新数据:
+============+=========+============+=============+====================+
| Threadpool | Threads | Iterations | Corei7-6700 | 2x Xeon E5-2696 v4 |
+============+=========+============+=============+====================+
| 100 | 100000 | 1000 | 1300 | 900 |
+------------+---------+------------+-------------+--------------------+
| 1000 | 100000 | 1000 | 1400 | 1000 |
+------------+---------+------------+-------------+--------------------+
| 10000 | 100000 | 1000 | 1470 | 1070 |
+------------+---------+------------+-------------+--------------------+
我在 32 核至强和 22 核旧至强机器上测试了相同的代码,模式相似:内核越少,多线程代码运行得越快。但是为什么?
重要说明:这是为了解决我原来的问题:
Why having more and faster cores makes my multithreaded software slower?
注意事项:
g++ ./threadpool.cpp -o ./tp -lpthread最佳答案
您正在将大量工作人员排入线程池,而这些工作人员只需很少的时间即可执行。因此,线程池的实现(不是 实际工作)成为瓶颈,特别是其互斥锁处理争用的方式。我尝试用 folly::CPUThreadPoolExecutor 替换 thread_pool , 哪种帮助:
thread_pool version:
2180 ms | thread_pool_size=100 num_workers=100000 loop_size=1000 affinity=0-23
2270 ms | thread_pool_size=1000 num_workers=100000 loop_size=1000 affinity=0-23
2400 ms | thread_pool_size=10000 num_workers=100000 loop_size=1000 affinity=0-23
530 ms | thread_pool_size=100 num_workers=100000 loop_size=1000 affinity=0-7
1930 ms | thread_pool_size=1000 num_workers=100000 loop_size=1000 affinity=0-7
2300 ms | thread_pool_size=10000 num_workers=100000 loop_size=1000 affinity=0-7
folly::CPUThreadPoolExecutor version:
830 ms | thread_pool_size=100 num_workers=100000 loop_size=1000 affinity=0-23
780 ms | thread_pool_size=1000 num_workers=100000 loop_size=1000 affinity=0-23
800 ms | thread_pool_size=10000 num_workers=100000 loop_size=1000 affinity=0-23
880 ms | thread_pool_size=100 num_workers=100000 loop_size=1000 affinity=0-7
1130 ms | thread_pool_size=1000 num_workers=100000 loop_size=1000 affinity=0-7
1120 ms | thread_pool_size=10000 num_workers=100000 loop_size=1000 affinity=0-7
我建议您(1) 在每个线程中做更多的工作; (2) 使用与 CPU 一样多的线程; (3) 使用更好的线程池。让我们将thread_pool_size设置为CPU的数量,并将loop_size乘以10:
thread_pool version:
1880 ms | thread_pool_size=24 num_workers=100000 loop_size=10000 affinity=0-23
4100 ms | thread_pool_size=8 num_workers=100000 loop_size=10000 affinity=0-7
folly::CPUThreadPoolExecutor version:
1520 ms | thread_pool_size=24 num_workers=100000 loop_size=10000 affinity=0-23
2310 ms | thread_pool_size=8 num_workers=100000 loop_size=10000 affinity=0-7
请注意,通过将每个线程的工作量增加 10 倍,我们实际上使 thread_pool 版本更快,而 folly::CPUThreadPoolExecutor 版本仅花费了 2 倍时间。让我们将 loop_size 乘以 10 倍以上:
thread_pool version:
28695 ms | thread_pool_size=24 num_workers=100000 loop_size=100000 affinity=0-23
81600 ms | thread_pool_size=8 num_workers=100000 loop_size=100000 affinity=0-7
folly::CPUThreadPoolExecutor version:
6830 ms | thread_pool_size=24 num_workers=100000 loop_size=100000 affinity=0-23
14400 ms | thread_pool_size=8 num_workers=100000 loop_size=100000 affinity=0-7
对于 folly::CPUThreadPoolExecutor,结果不言自明:在每个线程中做更多的工作可以使您更接近并行性带来的真正线性 yield 。而 thread_pool 似乎不能胜任这项任务;它无法正确处理这种规模的互斥锁争用。
这是我用来测试的代码(使用 gcc 5.5 编译,完全优化):
#include <chrono>
#include <cmath>
#include <iostream>
#include <memory>
#include <vector>
#define USE_FOLLY 1
#if USE_FOLLY
#include <folly/executors/CPUThreadPoolExecutor.h>
#include <folly/futures/Future.h>
#else
#include "threadpool.hpp"
#endif
int loop_size;
thread_local double dummy = 0.0;
void process(int num) {
double x = 0;
double sum = 0;
for (int i = 0; i < loop_size; ++i) {
x += 0.0001;
sum += sin(x) / cos(x) + cos(x) * cos(x);
}
dummy += sum; // prevent optimization
}
int main(int argc, char* argv[]) {
if (argc < 3) {
std::cerr << argv[0] << " [thread_pool_size] [threads] [sleep_time]"
<< std::endl;
exit(0);
}
int th_count = std::atoi(argv[1]);
#if USE_FOLLY
auto executor = std::make_unique<folly::CPUThreadPoolExecutor>(th_count);
#else
auto pool = std::make_unique<thread_pool>(th_count);
#endif
loop_size = std::stoi(argv[3]);
int max = std::stoi(argv[2]);
auto then = std::chrono::steady_clock::now();
#if USE_FOLLY
std::vector<folly::Future<folly::Unit>> futs;
for (int i = 0; i < max; ++i) {
futs.emplace_back(folly::via(executor.get()).then([i]() { process(i); }));
}
folly::collectAll(futs).get();
#else
for (int i = 0; i < max; ++i) {
pool->enqueue([i]() { process(i); });
}
pool = nullptr;
#endif
int diff = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - then)
.count();
std::cerr << "Time: " << diff << '\n';
return 0;
}
关于c++ - 为什么多线程代码在更快的机器上运行得更慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51390084/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串