【发布时间】:2018-11-14 13:13:27
【问题描述】:
我正在尝试使用最佳线程数(大约 20-30)下载大约 300-400 个图像文件,然后将这些图像写入 Android 的文件系统。问题是整个过程需要 10-13 分钟,我想通过高速互联网将其计时在 2-3 分钟左右
我认为这可以实现,因为那些 300-400 图像文件的大小仅为一些 KB(总大小约为 80-100 MB)
这是我下载和保存文件的代码
long t1 = System.currentTimeMillis();
Call<ResponseBody> call=apiService.fetchAttachmentDetail(att_id,token,true,device_id, 0.0f, 0.0f);
Response<ResponseBody> response = call.execute();
long t2 = System.currentTimeMillis();
Help.E("downloaded " + att_id + "and time taken in mili second " + (t2 - t1));
Help.E("content length- " + response.body().contentLength());
String str = response.headers().get("Content-Type");
if (str == null)
str = "/png";
String ext_type = str.substring(str.indexOf("/") + 1);
InputStream in = null;
FileOutputStream out = null;
ContextWrapper cw = new ContextWrapper(context);
String fileName = "";
File directory = cw.getDir(AttachmentDirName, Context.MODE_PRIVATE);
try {
in = response.body().byteStream();
fileName = String.valueOf(att_id) + "." + ext_type;
File file = new File(directory, fileName);
out = new FileOutputStream(file);
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} catch (IOException e) {
Log.d("Error", e.toString());
emitter.onError(e);
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
long t3 = System.currentTimeMillis();
Help.E("saved " + att_id + "time taken in saving the file " + (t3 - t2));
【问题讨论】:
-
using the optimal number of threads(around 20-30)。难以置信。在多少个核心上?请告诉我们您如何发现 20-30 是最佳值。 -
我不知道最佳数量应该是多少,但我用 20、30、50、100 个线程运行了这段代码,发现如果我们创建大量线程,那么线程创建开销会增加总时间,但使用 20-30 个线程,可以并行下载这 300-400 张图像。如果我错了,请纠正我!
-
你没有告诉你有多少核心。而且您没有解释为什么 20-30 是最佳的。好吧,我认为这根本不是最佳选择。
don't know what the optimal number should be。好吧,您可以轻松地对其进行测试。试试看嘛。现在不是 20-30 岁。 -
四核 1.4 GHz Cortex-A53!!!你能告诉我这个核心配置的最佳线程数吗?
-
不,我不能。我认为每个核心有两个。但是测试一下。很容易测试。首先确定核心数量,然后决定每个核心有多少线程。但首先使用 Vladyslav 的代码。太奇怪了,你没有对那个答案做出反应。
标签: android multithreading performance io storage