简体   繁体   English

多个异步协程以减少 Kotlin 中的执行时间

[英]Multiple async coroutine to reduce executed time in Kotlin

I had a list and I want to perform 1 heavy task with all elements to minimum executed times.我有一个列表,我想用所有元素执行 1 项繁重的任务,以最少的执行时间。 My solution is create a number of coroutines that equals to elements in list with dispatcher Default.我的解决方案是使用调度程序默认创建一些等于列表中元素的协程。

Example:例子:

list.map {
   async {
      // do heavy task
   }
}.awaitAll()

Assume that I had a map with 500 elements and my device has maximum 4 threads that can run parallel maximum 4 heavy tasks.假设我有一个包含 500 个元素的 map,我的设备最多有 4 个线程,可以并行运行最多 4 个繁重的任务。 As my understanding that will 4 threads do 4 tasks parallel, when one thread executed done, one task will be allocated to that thread and start.据我了解,4个线程将并行执行4个任务,当一个线程执行完成时,一个任务将分配给该线程并启动。 The other solution is create 4 coroutines for 4 threads and sequentially do 125 task per thread.另一种解决方案是为 4 个线程创建 4 个协程,并按顺序为每个线程执行 125 个任务。 Each threads run sequentially therefore it confined multiple time to allocate task to threads.每个线程按顺序运行,因此它限制了多次将任务分配给线程。 Therefore it faster than my solution.因此它比我的解决方案更快。 Is it right?这样对吗? If not, what is the best solution?如果不是,最好的解决方案是什么?

I use the following code.我使用以下代码。

It's for a List of a lot of elements that I need to transform into another object class.这是我需要转换为另一个 object class 的许多元素的列表。

/**
     * Method that converts the [FullStopsInfo] list into [Station] list.
     */
    private fun fastConvert(data: MutableList<FullStopsInfo>): Vector<Station> {
        var data1 = data
        val stations = Vector<Station>()

        var offset = 0
        val range = data1.size / Utils.availableCores()// your 4 cores

        val queue = mutableListOf<Deferred<Int>?>()

        val timeProccessing = measureTimeMillis {
            while (data1.isNotEmpty()) {
                val newRange = min(if(range == 0) 1 else range, data1.size)
                val tempTransfers = data1.subList(0, newRange)

                val preferredTask = addToList(tempTransfers, stations)//the transformation goes here
                queue.add(preferredTask)
                preferredTask.start()

                // Move to the next range
                data1 = data1.subList(newRange, data1.size)
                offset += newRange
            }

            runBlocking {
                queue.forEach {
                    it?.await()//wait until all procceses ended
                }
            }
        }

        Log.d(TAG, "End findSearchAllFullDataStation with $timeProccessing")
        return stations
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM