3

我想知道我是否需要测量经过的时间,那么这是一个好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 ms3电话回来了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 毫秒内返回,依此类推

所以我的问题是为什么多线程程序比上面的单线程程序要花费更多的时间?如果我的多线程程序中有一些漏洞,谁能帮我改进它?

4

1 回答 1

3

您的多线程程序可能会同时发出所有请求,这会给服务器带来更大的压力,这将导致它对所有请求的响应速度变慢。

顺便说一句,您进行更新的方式不是线程安全的,因此在多线程场景中,如果有足够的试验,您的计数可能会关闭。

例如,线程 A 和 B 都在 100 毫秒内同时返回。100 的直方图中的计数为 3。A 得到 3。B 得到 3。A 将 3 更新为 4。B 将 3 更新为 4。A 将值 4 放入直方图中。B 将值 4 放入直方图中。您现在有 2 个线程认为它们增加了计数,但直方图中的计数仅反映增加了一次。

于 2013-01-31T19:31:03.730 回答