Skip to content

Instantly share code, notes, and snippets.

@mmstick
Created November 13, 2014 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmstick/f3d758af73c63e98de31 to your computer and use it in GitHub Desktop.
Save mmstick/f3d758af73c63e98de31 to your computer and use it in GitHub Desktop.
GC and GCCGO unrolled loop benchmarks.
// AMD A4-5000 Quad-Core 1.5GHz APU
// GC benchmark
// Normal For Loop : 669.966032ms
// Double Unrolled Loop: 422.242497ms
// Triple Unrolled Loop: 363.525022ms
// Quad Unrolled Loop : 281.522688ms
// Octo Unrolled loop : 312.757938ms
// GCCGO -O1 benchmark
// Normal For Loop : 200.698ms
// Double Unrolled Loop: 67.139ms
// Triple Unrolled Loop: 44.696ms
// Quad Unrolled Loop : 33.559ms
// Octo Unrolled loop : 16.783ms
package main
import "fmt"
import "time"
// loopOne is a regular idiomatic Go for loop.
func loopOne(start time.Time) time.Duration {
x := 0
for index := 0; index < 100000000; index++ {
if index % 5 == 0 { x += index }
}
return time.Since(start)
}
// loopTwo is a double-unrolled for loop
func loopTwo(start time.Time) time.Duration {
x := 0
for index := 0; index < 100000000; index += 2 {
if index % 5 == 0 { x += index }
if index+1 % 5 == 0 { x += index+1 }
}
return time.Since(start)
}
// loopThree is a triple-unrolled for loop
func loopThree(start time.Time) time.Duration {
x := 0
for index := 0; index < 100000000; index += 3 {
if index % 5 == 0 { x += index }
if index+1 % 5 == 0 { x += index+1 }
if index+2 % 5 == 0 { x += index+2 }
}
return time.Since(start)
}
// loopFour is a quad-unrolled for loop
func loopFour(start time.Time) time.Duration {
x := 0
for index := 0; index < 100000000; index += 4 {
if index % 5 == 0 { x += index }
if index+1 % 5 == 0 { x += index+1 }
if index+2 % 5 == 0 { x += index+2 }
if index+3 % 5 == 0 { x += index+3 }
}
return time.Since(start)
}
// loopEight is an octo-unrolled for loop
func loopEight(start time.Time) time.Duration {
x := 0
for index := 0; index < 100000000; index += 8 {
if index % 5 == 0 { x += index }
if index+1 % 5 == 0 { x += index+1 }
if index+2 % 5 == 0 { x += index+2 }
if index+3 % 5 == 0 { x += index+3 }
if index+4 % 5 == 0 { x += index+4 }
if index+5 % 5 == 0 { x += index+5 }
if index+6 % 5 == 0 { x += index+6 }
if index+7 % 5 == 0 { x += index+7 }
}
return time.Since(start)
}
func main() {
fmt.Println("Normal For Loop :", loopOne(time.Now()))
fmt.Println("Double Unrolled Loop:", loopTwo(time.Now()))
fmt.Println("Triple Unrolled Loop:", loopThree(time.Now()))
fmt.Println("Quad Unrolled Loop :", loopFour(time.Now()))
fmt.Println("Octo Unrolled loop :", loopEight(time.Now()))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment