Skip to content

Instantly share code, notes, and snippets.

@soypat
Created February 12, 2021 18:02
Show Gist options
  • Save soypat/83f9358661c44656c7edbff03863a558 to your computer and use it in GitHub Desktop.
Save soypat/83f9358661c44656c7edbff03863a558 to your computer and use it in GitHub Desktop.
Cgo usleep vs. pure Go time.Sleep. Run with `go test -bench=.`
package ctest
// #include <time.h>
// void wait(int usec)
// {
// usleep(usec);
// }
import "C"
import "time"
func CUsleep(i int) {
C.wait(C.int(i))
}
func GUsleep(i int) {
time.Sleep(time.Duration(i) * 1000)
}
package ctest_test
import (
"bench/ctest"
"testing"
)
func benchGUSleep(u int, b *testing.B) {
for i := 0; i < b.N; i++ {
ctest.GUsleep(u)
}
}
func benchCUSleep(u int, b *testing.B) {
for i := 0; i < b.N; i++ {
ctest.CUsleep(u)
}
}
func BenchmarkCUsleep0(b *testing.B) { benchCUSleep(0, b) }
func BenchmarkCUsleep1(b *testing.B) { benchCUSleep(1, b) }
func BenchmarkCUsleep2(b *testing.B) { benchCUSleep(2, b) }
func BenchmarkCUsleep10(b *testing.B) { benchCUSleep(10, b) }
func BenchmarkCUsleep50(b *testing.B) { benchCUSleep(50, b) }
func BenchmarkCUsleep100(b *testing.B) { benchCUSleep(100, b) }
func BenchmarkCUsleep1000(b *testing.B) { benchCUSleep(1000, b) }
func BenchmarkGUsleep0(b *testing.B) { benchGUSleep(0, b) }
func BenchmarkGUsleep1(b *testing.B) { benchGUSleep(1, b) }
func BenchmarkGUsleep2(b *testing.B) { benchGUSleep(2, b) }
func BenchmarkGUsleep10(b *testing.B) { benchGUSleep(10, b) }
func BenchmarkGUsleep50(b *testing.B) { benchGUSleep(50, b) }
func BenchmarkGUsleep100(b *testing.B) { benchGUSleep(100, b) }
func BenchmarkGUsleep1000(b *testing.B) { benchGUSleep(1000, b) }
@ljx0517
Copy link

ljx0517 commented Nov 5, 2021

oh dude~.thanks~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment