【发布时间】:2015-02-20 19:13:54
【问题描述】:
我使用了两种不同的方法来测量线程的时间,但结果不匹配
**Public void Main()**
{
Timer timer = new Timer();
int timetotal;
timer.start();
int numberOfThreads=5;
ExecutorService pool= Executors.newFixedThreadPool(numberOfThreads);
List<Future<Boolean>> futureList = new ArrayList<Future<Boolean>>();
Set<ReadProcess_MongoDB> callList = new HashSet<ReadProcess_MongoDB>();
CompletionService<ReadProcess_MongoDB> taskCompletionService;
taskCompletionService = new ExecutorCompletionService<ReadProcess_MongoDB>(pool);
Collection<Callable<ReadProcess_MongoDB>> list;
list = new LinkedList<Callable<ReadProcess_MongoDB>>();
for(int i=0;i<numberOfThreads;i++)
list.add((Callable<ReadProcess_MongoDB>) new ReadProcess_MongoDB(i));
try {
for (Callable<ReadProcess_MongoDB> callable : list) {
taskCompletionService.submit(callable);
}
for (int i = 0; i < list.size(); i++) {
Future<ReadProcess_MongoDB> result = taskCompletionService.take();
}
} catch (InterruptedException e) {
// no real error handling. Don't do this in production!
e.printStackTrace();
} catch (ExecutionException e) {
// no real error handling. Don't do this in production!
e.printStackTrace();
}
finally {
pool.shutdown();
System.out.println("Done :)");
timer.stop();
System.out.println("Total consumed Time"+ timer.elapsed());
}
其他时间我输入了 Call method()
**public String call()**
{
Timer timer = new Timer();
int timetotal;
timer.start();
DBCursor cursor = coll.find(whereQuery);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(ReadProcess_MongoDB.class.getName()).log(Level.SEVERE, null, ex);
}
timer.stop();
usedTimeForQueryProcess = timer.elapsed();
System.out.println("Thread Number="+this.threadNumber+ " MongoDB_readQuery used time "+usedTimeForQueryProcess);
System.out.println("runing.....");
return Objects.toString(usedTimeForQueryProcess);
}
在调用函数中,每个线程的系统打印时间和主函数中只显示总时间。这里我尝试手动检查,但两个时间不匹配。但更大的问题是主函数显示的时间少于所有线程的总时间(调用函数)。
我也尝试从 Call 函数中返回使用的时间,但这也会产生转换为 long 的问题(尤其是运行时问题)。
两个功能的时间
主要功能时间=289
调用函数时间=510(5个线程)。
请有人解释为什么会发生这种情况以及我如何进行正确的测量?
【问题讨论】:
-
嗯,你想通过测量这个来达到什么目的?您是否有特定的问题要解决,或者这只是求知欲?
-
@fge 我正在开发应用程序来测试不同类型数据库(sql 和 noSql)的工作负载性能(读/写)。
标签: java multithreading time