Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

runtime: Two dimensional array access in go vs C #11587

Closed
oldmonkABA opened this issue Jul 4, 2015 · 2 comments
Closed

runtime: Two dimensional array access in go vs C #11587

oldmonkABA opened this issue Jul 4, 2015 · 2 comments

Comments

@oldmonkABA
Copy link

I have the following code in C where I attempt to access elements of a two D int array

include <stdio.h>

include <time.h>

void main ()
{

int tr_nextstate[8][2] = {{0, 4}, {4, 0}, {5, 1}, {1, 5}, {2, 6}, {6, 2}, {7, 3}, {3, 7}};
int i, j,next_state=0;

clock_t start, end;
double cpu_time_used;
start = clock();

for (i = 0; i < 100000000; i++)
{
j = i % 2;
next_state = tr_nextstate[next_state][j];

}
end = clock();

cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC*1000;
printf("fun() took %f milliseconds to execute \n", cpu_time_used);

}

I have the same code in go :

package main

import (
"fmt"
"time"
)

func main() {
tr_nextstate := [][]int{{0, 4}, {4, 0}, {5, 1}, {1, 5}, {2, 6}, {6, 2}, {7, 3}, {3, 7}}

next_state := 0
var j int
startTime := time.Now()
for i := 0; i < 100000000; i++ {
    j:= i % 2
    next_state = tr_nextstate[next_state][j]

}
fmt.Printf("\nTime Elapsed : %v", time.Since(startTime))

}

When I run both the codes in my machine.
C - code gives a runtime of roughly 400 milliseconds
Go-code gives a runtime of roughtly 550 milliseconds

Can anyone throw light on why so?

My machine runs kubuntu 15.04 with i5 @2.4GHz with 16GB RAM

@davecheney
Copy link
Contributor

Can anyone throw light on why so?

Go programs always bounds check array access, where C programs do not.

@davecheney
Copy link
Contributor

Please raise this question on the mailing list, golang-nuts. The issue tracker is only for bugs.

@mikioh mikioh changed the title Two dimensional array access in go vs C runtime: Two dimensional array access in go vs C Jul 7, 2015
@golang golang locked and limited conversation to collaborators Jul 11, 2016
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants