Skip to content

Instantly share code, notes, and snippets.

@FooBarWidget
Created September 10, 2018 12:23
Show Gist options
  • Save FooBarWidget/39136618063e5ac6aeb9ff28a4387251 to your computer and use it in GitHub Desktop.
Save FooBarWidget/39136618063e5ac6aeb9ff28a4387251 to your computer and use it in GitHub Desktop.
package main
/*
#include <sys/time.h>
#include <pthread.h>
static unsigned int
plusOne(unsigned int x) {
return x + 1;
}
static void
benchmarkMutex(unsigned int iterations) {
pthread_mutex_t m;
pthread_mutex_init(&m, NULL);
for (unsigned int i = 0; i < iterations; i++) {
pthread_mutex_lock(&m);
pthread_mutex_unlock(&m);
}
}
static void
benchmarkTime(unsigned int iterations) {
for (unsigned int i = 0; i < iterations; i++) {
struct timeval tv;
gettimeofday(&tv, NULL);
}
}
*/
import "C"
import (
"fmt"
"os"
"strconv"
"sync"
"time"
)
func plusOne(x uint) uint {
return x + 1
}
func main() {
var modifier uint
var result uint
var mutex sync.Mutex
var iterations uint
if len(os.Args) > 1 {
i, _ := strconv.ParseUint(os.Args[1], 10, 32)
iterations = uint(i)
modifier = 1
} else {
iterations = 100000
modifier = 2
}
a := time.Now()
for i := uint(0); i < iterations; i++ {
result += uint(C.plusOne(C.uint(i))) + modifier
}
b := time.Now()
for i := uint(0); i < iterations; i++ {
result += plusOne(i) + modifier
}
c := time.Now()
for i := uint(0); i < iterations; i++ {
mutex.Lock()
mutex.Unlock()
}
d := time.Now()
C.benchmarkMutex(C.uint(iterations))
e := time.Now()
C.benchmarkTime(C.uint(iterations))
f := time.Now()
fmt.Printf("CGo plusOne: %v ns/call\n", float64(b.Sub(a))/float64(iterations))
fmt.Printf("Go plusOne: %v ns/call\n", float64(c.Sub(b))/float64(iterations))
fmt.Printf("Go mutex : %v ns/call\n", float64(d.Sub(c))/float64(iterations))
fmt.Printf("C mutex : %v ns/call\n", float64(e.Sub(d))/float64(iterations))
fmt.Printf("C time : %v ns/call\n", float64(f.Sub(e))/float64(iterations))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment