我写了几个 Java 类——SingleThreadedCompute 和 MultithreadedCompute——来证明一个事实(或者我一直认为是一个事实!)如果你并行计算-centric(无 I/O)单核机器上的任务,你不会得到加速。事实上,我的理解是并行化这些任务实际上会减慢速度,因为现在你必须处理上下文切换开销。好吧,我运行了这些类,并行版本出人意料地运行得更快:单线程版本在我的机器上始终以略高于 7 秒的速度运行,而多线程版本在我的机器上始终以略高于 6 秒的速度运行。谁能解释这是怎么可能的?
如果有人想自己查看或尝试,这里有类(class)。
public final class SingleThreadedCompute {
private static final long _1B = 1000000000L; // one billion
public static void main(String[] args) {
long startMs = System.currentTimeMillis();
long total = 0;
for (long i = 0; i < _1B; i++) { total += i; }
System.out.println("total=" + total);
long elapsedMs = System.currentTimeMillis() - startMs;
System.out.println("Elapsed time: " + elapsedMs + " ms");
}
}
这是多线程版本:
public final class MultithreadedCompute {
private static final long _1B = 1000000000L; // one billion
private static final long _100M = _1B / 10L;
public static void main(String[] args) {
long startMs = System.currentTimeMillis();
System.out.println("Creating workers");
Worker[] workers = new Worker[10];
for (int i = 0; i < 10; i++) {
workers[i] = new Worker(i * _100M, (i+1) * _100M);
}
System.out.println("Starting workers");
for (int i = 0; i < 10; i++) { workers[i].start(); }
for (int i = 0; i < 10; i++) {
try {
workers[i].join();
System.out.println("Joined with thread " + i);
} catch (InterruptedException e) { /* can't happen */ }
}
System.out.println("Summing worker totals");
long total = 0;
for (int i = 0; i < 10; i++) { total += workers[i].getTotal(); }
System.out.println("total=" + total);
long elapsedMs = System.currentTimeMillis() - startMs;
System.out.println("Elapsed time: " + elapsedMs + " ms");
}
private static class Worker extends Thread {
private long start, end;
private long total;
public Worker(long start, long end) {
this.start = start;
this.end = end;
}
public void run() {
System.out.println("Computing sum " + start + " + ... + (" + end + " - 1)");
for (long i = start; i < end; i++) { total += i; }
}
public long getTotal() { return total; }
}
}
这是运行单线程版本的输出:
total=499999999500000000
Elapsed time: 7031 ms
这是运行多线程版本的输出:
Creating workers
Starting workers
Computing sum 0 + ... + (100000000 - 1)
Computing sum 100000000 + ... + (200000000 - 1)
Computing sum 200000000 + ... + (300000000 - 1)
Computing sum 300000000 + ... + (400000000 - 1)
Computing sum 400000000 + ... + (500000000 - 1)
Computing sum 500000000 + ... + (600000000 - 1)
Computing sum 600000000 + ... + (700000000 - 1)
Computing sum 700000000 + ... + (800000000 - 1)
Computing sum 800000000 + ... + (900000000 - 1)
Computing sum 900000000 + ... + (1000000000 - 1)
Joined with thread 0
Joined with thread 1
Joined with thread 2
Joined with thread 3
Joined with thread 4
Joined with thread 5
Joined with thread 6
Joined with thread 7
Joined with thread 8
Joined with thread 9
Summing worker totals
total=499999999500000000
Elapsed time: 6172 ms
编辑:环境信息:
不知道如何证明它是单核机器,除了通过说明上面的规范并指出当我购买机器时(2005 年 8 月),单核是标准的,我没有升级到多核(如果那甚至是一个选择……我不记得了)。如果 Windows 中的某个地方我可以检查系统属性(显示上面的信息)以外的内容,请告诉我,我会检查。
这里有五个连续的 ST 和 MT 运行:
五个单线程运行:
总计=499999999500000000 耗时:7000 毫秒
总计=499999999500000000 耗时:7031 毫秒
总计=499999999500000000 耗时:6922 毫秒
总计=499999999500000000 耗时:6968 毫秒
总计=499999999500000000 耗时:6938 毫秒
五个多线程运行:
总计=499999999500000000 耗时:6047 毫秒
总计=499999999500000000 耗时:6141 毫秒
总计=499999999500000000 耗时:6063 毫秒
总计=499999999500000000 耗时:6282 毫秒
总计=499999999500000000 耗时:6125 毫秒
最佳答案
这可能是由于超线程和/或流水线造成的。
来自维基百科 on hyper-threading :
Hyper-threading is an advancement over super-threading. Hyper-threading (officially termed Hyper-Threading Technology or HTT) is an Intel-proprietary technology used to improve parallelization of computations (doing multiple tasks at once) performed on PC microprocessors. A processor with hyper-threading enabled is treated by the operating system as two processors instead of one. This means that only one processor is physically present but the operating system sees two virtual processors, and shares the workload between them.
来自维基百科 on piplining :
In computing, a pipeline is a set of data processing elements connected in series, so that the output of one element is the input of the next one. The elements of a pipeline are often executed in parallel or in time-sliced fashion
关于java - 意外的多线程结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/519099/
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
导读语言模型给我们的生产生活带来了极大便利,但同时不少人也利用他们从事作弊工作。如何规避这些难辨真伪的文字所产生的负面影响也成为一大难题。在3月9日智源Live第33期活动「DetectGPT:判断文本是否为机器生成的工具」中,主讲人Eric为我们讲解了DetectGPT工作背后的思路——一种基于概率曲率检测的用于检测模型生成文本的工具,它可以帮助我们更好地分辨文章的来源和可信度,对保护信息真实、防止欺诈等方面具有重要意义。本次报告主要围绕其功能,实现和效果等展开。(文末点击“阅读原文”,查看活动回放。)Ericmitchell斯坦福大学计算机系四年级博士生,由ChelseaFinn和Chri
这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/
HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候
遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg