import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTargetWithTests
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.4.10'}
group ='me.10221903'
version ='1.0-SNAPSHOT'
repositories {mavenCentral()}
kotlin {def hostOs = System.getProperty("os.name")def isMingwX64 = hostOs.startsWith("Windows")
KotlinNativeTargetWithTests nativeTarget
if(hostOs =="Mac OS X") nativeTarget =macosX64('native')elseif(hostOs =="Linux") nativeTarget =linuxX64("native")elseif(isMingwX64) nativeTarget =mingwX64("native")elsethrownewGradleException("Host OS is not supported in Kotlin/Native.")
nativeTarget.with {
binaries {
executable {
entryPoint ='main'}}}
sourceSets {
nativeMain {
dependencies {// implementation "com.autodesk:coroutineworker:0.6.2"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9-native-mt"}}
nativeTest {}}}
测试1:原生单核协程对比
package main
import("fmt""sync""time")funcfib(n int)int{if n <=1{return n
}returnfib(n-1)+fib(n-2)}funcmassiveRun(action func()){
n :=100// 可修改参数
k :=1000
t0 := time.Now()var wg sync.WaitGroup
for i :=0; i < n; i++{
wg.Add(1)gofunc(){for j :=0; j < k; j++{action()}
wg.Done()}()}
wg.Wait()
elapsed := time.Since(t0)
fmt.Println("Completed 100000 actions in ", elapsed)}funcmain(){
runtime.GOMAXPROCS(1)massiveRun(func(){fib(20)// 可修改参数})}
Kotlin测试代码
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.runBlocking
import kotlin.system.measureTimeMillis
funfib(n: Int): Int {if(n <=1){return n
}returnfib(n-1)+fib(n-2)}suspendfunmassiveRun(action:suspend()-> Unit){val n =100// 启动的协程数量val k =1000// 每个协程重复执行同一动作的次数val time = measureTimeMillis {
coroutineScope {// 协程的作用域repeat(n){
launch {repeat(k){action()}}}}}println("Completed ${n * k} actions in $time ms")}funmain()= runBlocking {withContext(Dispatchers.Default){
massiveRun {fib(20)}}}