【问题标题】:Java: how to test fine-granularity in multithreaded programJava:如何在多线程程序中测试细粒度
【发布时间】:2013-09-21 20:56:18
【问题描述】:

在 Java 中,我有简单的多线程代码:

public class ThreadedAlgo {

    public static final int threadsCount = 3;

    public static void main(String[] args) {

        // start timer prior computation
        time = System.currentTimeMillis();

        // create threads
        Thread[] threads = new Thread[threadsCount];

        class ToDo implements Runnable {
            public void run() { ... }
        }

        // create job objects
        for (int i = 0; i < threadsCount; i++) {
            ToDo job = new ToDo();
            threads[i] = new Thread(job);
        }

        // start threads
        for (int i = 0; i < threadsCount; i++) {
            threads[i].start();
        }

        // wait for threads above to finish
        for (int i = 0; i < threadsCount; i++) {
            try {
                threads[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // display time after computation
        System.out.println("Execution time: " + (System.currentTimeMillis() - time));

    }

}

它工作正常,现在我想为 2 或 3 个线程运行它并计算每个线程的计算时间。然后我会比较时间:注意t1t2,如果|t1 - t2| &lt; small epsilon,我会说我的算法在某些给定条件下执行的粒度很细,即线程花费的时间相对相同。

如何测量线程的时间?

【问题讨论】:

  • 我认为使用分析工具会更好地为您服务,而不是尝试读取计时器。即使有计时器,老实说,我也不相信任何小于毫秒的数字。 “纳秒”结果纯属科幻小说:恕我直言。建议:这里有一个关于 Eclipse Profiler 的优秀教程:eclipse.org/tptp/home/documents/tutorials/profilingtool/…

标签: java multithreading


【解决方案1】:

在线程(作业)方法的开始和结束处使用System.nanoTime() 来计算每次调用所花费的总时间。在您的情况下,所有线程都将以相同的(默认)优先级执行,其中时间片应该分配得相当公平。如果你的线程是互锁的,出于同样的原因使用“公平锁”;例如new ReentrantLock(true);

【讨论】:

  • 不,我的线程是独立的,非常适合测量。 System.currentTimeMillis() 不是很好的时间测量方式吗?
  • 没关系,我只是更喜欢尽可能高的分辨率来处理这些事情。如果线程运行的时间不足以实现毫秒级分辨率,则线程创建的开销可能会成为更大的问题。
  • 请注意,System.nanoTime 可能会返回看似随机的值。见stackoverflow.com/questions/510462/…
【解决方案2】:

在 Run 方法中添加计时逻辑

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多