Created
January 25, 2023 11:54
-
-
Save ericwomer/8921f3123392a9451ac89a4957c3ebbd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.CoroutineScope | |
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.async | |
import kotlinx.coroutines.launch | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.runBlocking | |
import kotlinx.coroutines.withContext | |
import kotlin.coroutines.coroutineContext | |
fun main(args: Array<String>) = runBlocking<Unit> { | |
asyncTest() | |
} | |
suspend fun asyncTest() { | |
val startTime = System.currentTimeMillis() | |
val count = 826 | |
val cores = Runtime.getRuntime().availableProcessors() | |
val quotent: Int = count / cores | |
val remainder: Int = count % cores | |
var asyncCount = 0 | |
var forCount = 0 | |
val scope = CoroutineScope( Dispatchers.Default) | |
var dotList = mutableListOf<String>("") | |
var numberList = mutableListOf<Int>() | |
var iList = mutableListOf<Int>() | |
var jList = mutableListOf<Int>() | |
println("count is $count, number of cores is $cores, the quotent is $quotent and the reminader is $remainder") | |
withContext(coroutineContext) { | |
for(i in 1 .. (count - remainder) step (cores )) { | |
forCount = i + (cores - 1) | |
println("forCount == $forCount") | |
asyncCount++ | |
async(Dispatchers.Default) { | |
for (j in i..forCount) { | |
jList.add(j) | |
iList.add(i) | |
dotList.add(".") | |
delay(2) // Work | |
} | |
} | |
numberList.add(asyncCount) | |
} | |
} | |
asyncCount++ | |
forCount++ | |
numberList.add(asyncCount) | |
println("forCount == $forCount") | |
if(remainder != 0) { | |
withContext(coroutineContext) { | |
async(Dispatchers.Default) { | |
for (i in forCount..(forCount + remainder)) { | |
dotList.add(".") | |
delay(2) // Work | |
} | |
} | |
} | |
} | |
println("iList.count() == ${iList.count()}") | |
iList.sort() | |
println("iList == $iList") | |
println("asyncCount == $asyncCount") | |
println("Number of dots == ${dotList.count()}") | |
println("Time elapsed: ${elapseMillis(startTime = startTime)}ms") | |
println("Dots: ${dotList.toString()}") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment