我想知道我是否需要测量经过的时间,那么这是一个好Single Threaded Program
方法还是Multithreading Program
一个好的方法。
下面是我的单线程程序,它正在测量我们的服务时间-
private static void serviceCall() {
histogram = new HashMap<Long, Long>();
keys = histogram.keySet();
long total = 5;
long runs = total;
while (runs > 0) {
long start_time = System.currentTimeMillis();
result = restTemplate.getForObject("SOME URL",String.class);
long difference = (System.currentTimeMillis() - start_time);
Long count = histogram.get(difference);
if (count != null) {
count++;
histogram.put(Long.valueOf(difference), count);
} else {
histogram.put(Long.valueOf(difference), Long.valueOf(1L));
}
runs--;
}
for (Long key : keys) {
Long value = histogram.get(key);
System.out.println("MEASUREMENT " + key + ":" + value);
}
}
我从这个单线程程序得到的输出是 - 总调用是5
MEASUREMENT 163:1
MEASUREMENT 42:3
MEASUREMENT 47:1
这意味着1
电话回来了163 ms
。3
电话回来了42 ms
等等。
而且我也尝试过使用Multithreaded program
来测量经过的时间。意思是用少量线程并行访问服务,然后测量每个线程占用了多少。
下面也是该代码 -
//create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(10);
// queue some tasks
for (int i = 0; i < 1 * 5; i++) {
service.submit(new ThreadTask(i, histogram));
}
public ThreadTask(int id, HashMap<Long, Long> histogram) {
this.id = id;
this.hg = histogram;
}
@Override
public void run() {
long start_time = System.currentTimeMillis();
result = restTemplate.getForObject("", String.class);
long difference = (System.currentTimeMillis() - start_time);
Long count = hg.get(difference);
if (count != null) {
count++;
hg.put(Long.valueOf(difference), count);
} else {
hg.put(Long.valueOf(difference), Long.valueOf(1L));
}
}
以下是我从上述程序中得到的结果-
{176=1, 213=1, 182=1, 136=1, 155=1}
一个电话在 176 毫秒内返回,依此类推
所以我的问题是为什么多线程程序比上面的单线程程序要花费更多的时间?如果我的多线程程序中有一些漏洞,谁能帮我改进它?