-3

我有一个简单的生产者(1)和消费者(从 1-50 不等)问题,生产者只是在队列中添加元素,消费者读取它。我正在尝试获得 100% 的 CPU 利用率。

目前我的利用率为 20%。而且我无法获得 100% 的 CPU 利用率。我希望我所有的 CPU 用于更快地执行操作。我应该看什么?

机器:运行 Windows 8 和 Java 7 的 i7(第 4 代 - 具有超线程的四代码)。

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Semaphore;
/*
 * Purpose is to test system clock granularity
 */

public class ClockGranularity{
        private static final int MaxExecutionTimeMsec = 6;
        //60*1000 milliseconds
        private static float delta = 0.01f;
        //Inter-arrival Time(IAT): in milliseconds
        static final int ArraySize =(int) ((float)MaxExecutionTimeMsec/delta);
        private static final int convertMilliToNano = 1000000;

        private static String getTime() {
                DateFormat format = new SimpleDateFormat("dd-MMM-yy HH:mm:ss");
                Calendar cal = Calendar.getInstance();
                return format.format(cal.getTime());
        }
        /*
         * Invoke 1 producer vs 1,2,3 consumers
         * Write consumer to file
         */
        public static void main(String args[]) {
                ClockGranularity.delta = delta*convertMilliToNano;
                long execStartTime = System.currentTimeMillis();
                long experimentStartTime = System.nanoTime();
                long execDuration, experimentRuntime;
                Buffer requestQueue = new Buffer();
                Producer producer = new Producer(requestQueue);
                Consumer consumer = new Consumer(requestQueue);
                Consumer consumer2 = new Consumer(requestQueue);
                Consumer consumer3 = new Consumer(requestQueue);
                consumer.start();
                consumer2.start();
                consumer3.start();
                do {
                        execDuration = System.currentTimeMillis() - execStartTime;
                        experimentRuntime = System.nanoTime() - experimentStartTime;
                        if(experimentRuntime >= delta) {
                                experimentStartTime = System.nanoTime();
                        producer.run();
                        }
                } while (execDuration <= MaxExecutionTimeMsec);
                consumer.interrupt();
                consumer2.interrupt();
                consumer3.interrupt();
                delta/=convertMilliToNano;
                try {
                        String producerFile = "Producer-" + delta + " msec @" + getTime();
                        printToFile(producerFile,requestQueue.getQueue());
                        String consumerFile = "Consumer-" + delta + " msec@" + getTime();
                        printToFile(consumerFile, consumer.getValidateConsumerArray());
                        consumerFile = "Consumer2-" + delta + " msec@" + getTime();
                        printToFile(consumerFile, consumer2.getValidateConsumerArray());
                        consumerFile = "Consumer3-" + delta + " msec@" + getTime();
                        printToFile(consumerFile, consumer3.getValidateConsumerArray());
                } catch (IOException e) {
                        e.printStackTrace();
                }
        }
        public static void printToFile(String outputFileName,Queue<Integer> requestQueue) throws IOException{
                outputFileName = outputFileName.replace(':', '-');
                String lineSeparator = System.lineSeparator();
                File directory = new File("Practice Coding\\src\\ClockGranularity Test results\\Semaphore and Queue\\");
                File file = File.createTempFile(outputFileName, ".txt",directory);
                FileWriter writer = new FileWriter(file);
                writer.append("Index \tQueue Contents" + lineSeparator);
                int size = requestQueue.size();
                String summary = "queue<>" + size;
                for(int i = 0; i<size; i++) {
                        String temp = i + " ticks  \t" + requestQueue.poll();
                        System.out.println(temp);
                        writer.append(temp + lineSeparator);
                }
                writer.append(lineSeparator + "Summary: " + lineSeparator);
                writer.append(summary + lineSeparator);
                System.out.println(outputFileName + " " + summary);
                writer.close();
        }
}
class Buffer {
        private Queue<Integer> requestsQueue;
        Semaphore accessQueue;
        Buffer() {
                requestsQueue = new LinkedList<Integer>();
                accessQueue = new Semaphore(1);
        }
        public void put(Integer tick) throws InterruptedException {
                accessQueue.acquire();
                requestsQueue.add(tick);
                accessQueue.release();
        }
        public synchronized int get() throws InterruptedException {
                int tick;
                while(requestsQueue.size() == 0) {
                        try {
                                wait();
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                }
                accessQueue.acquire();
                tick = requestsQueue.poll();
                accessQueue.release();
                return tick;
        }
        public Queue<Integer> getQueue() {
                return requestsQueue;
        }
}

class Consumer extends Thread{
        private Buffer bufferQueue;
        private Queue<Integer> validateConsumer;
        Consumer(Buffer requestQueue) {
                bufferQueue = requestQueue;
                validateConsumer = new LinkedList<Integer>();
        }
        public void run() {
                while(true) {
                        int i;
                        try {
                                i = bufferQueue.get();
                                validateConsumer.add(i);
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                }
        }
        public Queue<Integer> getValidateConsumerArray() {
                return validateConsumer;
        }
}

class Producer extends Thread{
        public int tick = 0;
        private Buffer bufferQueue;
        Producer(Buffer requestQueue) {
                bufferQueue = requestQueue;    
        }
        public void run() {
                try {
                        bufferQueue.put(tick++);
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }
        }
}
4

2 回答 2

1

你可以做的事情:

- 不要进行繁忙的循环(时间查询可能会降低您的利用率),如果您将生产者代码代码放在 while(true) 中,就像您对消费者所做的那样,让主线程休眠 MaxExecutionTimeMsec 时间,看看是否有区别,并像对消费者一样对生产者进行中断。

- 这与其通常的用法相反,但运行一个特殊的分析器并查看在哪里花费了多少时间。如果它不是业务部分(例如等待锁定获取),请在那里重新设计。

- 如果性能是关键并且您拥有多核 p 处理器,您可能需要研究自旋锁。在某些摊销方案中,上下文切换可能比自旋锁更昂贵。

于 2013-11-02T00:58:15.087 回答
1

你的Buffer实现是错误的。它本质上是序列化读/写,因此性能很差。您需要改为使用或实现读写器锁

于 2013-11-02T00:59:00.953 回答