Concurrency slowing down go codeIs this a good way of managing parallel go routines when I care about...

A peculiar integral identity

Should we avoid writing fiction about historical events without extensive research?

Plagiarism of code by other PhD student

Where is the fallacy here?

Would the melodic leap of the opening phrase of Mozart's K545 be considered dissonant?

Are there other characters in the Star Wars universe who had damaged bodies and needed to wear an outfit like Darth Vader?

Why is it "take a leak?"

Quitting employee has privileged access to critical information

Misplaced tyre lever - alternatives?

Did Amazon pay $0 in taxes last year?

If nine coins are tossed, what is the probability that the number of heads is even?

Relationship between the symmetry number of a molecule as used in rotational spectroscopy and point group

Why do phishing e-mails use faked e-mail addresses instead of the real one?

Was it really inappropriate to write a pull request for the company I interviewed with?

Called into a meeting and told we are being made redundant (laid off) and "not to share outside". Can I tell my partner?

Meaning of word ягоза

Can an earth elemental drown/bury its opponent underground using earth glide?

Why did the Cray-1 have 8 parity bits per word?

School performs periodic password audits. Is my password compromised?

Why are special aircraft used for the carriers in the United States Navy?

Why is my Contribution Detail Report (native CiviCRM Core report) not accurate?

is 'sed' thread safe

Make me a metasequence

Find maximum of the output from reduce



Concurrency slowing down go code


Is this a good way of managing parallel go routines when I care about ordering of results?Concurrency interviewConsumer/Producer (Concurrency) - Exception HandlingConcurrency and locking in a chat serverConcurrency-safe stack implementation in GoConcurrency using immutabilityImplementation of a cellular automata to model breast cancerUse of concurrency to generate combinationsConcurrency-safe cache in GoLocate substrings within a file













0












$begingroup$


I am working through this problem on project euler.



Basic purpose of the code:



/*
if n is even n -> n/2
if n is odd n -> 3n + 1
which starting number under 1 million produces the longest sequence?
*/


The trouble with the code is that when I implement concurrency as I have, the program runs considerably more slowly than when I am just returning values directly from the get_seq_len function. Am I implementing concurrency incorrectly? Or is the program just not complex enough that there is speed to be gained from concurrency or something?



package main

import ("fmt";"math";"time")


This function takes a number x and then using the formula described in the above comment block creates a sequence of numbers from it until the number 1 is reached. Originally I had the function simply returning the length of the sequence, but now I have it sending the length to the specified channel.



func get_seq_len(x int, c chan int) {
var count int = 1
for {
if x == 1 {
break
} else if x%2 == 0 {
x = x / 2
} else {
x = 3 * x + 1
}
count++
}
// return count + 1
c <- count + 1
}


Here the main function just step through every number from 1 to whatever the max is and then tests the length of the sequence for that number. I use channel c to pass the sequenced length back to main().



func main() {
start := time.Now()
var max int = int(math.Pow(10,6))
// var max int = int(math.Pow(3,3))
var max_length int = 0
var max_num int = 0
c := make(chan int, 50)

for i:=1; i<max; i++ {
// length := get_seq_len(i, c)
go get_seq_len(i, c)
length := <-c

if length > max_length { max_length = length; max_num = i }
}

fmt.Println(max_num)
t := time.Now()
elapsed := t.Sub(start)
fmt.Println(elapsed)

}








share









$endgroup$

















    0












    $begingroup$


    I am working through this problem on project euler.



    Basic purpose of the code:



    /*
    if n is even n -> n/2
    if n is odd n -> 3n + 1
    which starting number under 1 million produces the longest sequence?
    */


    The trouble with the code is that when I implement concurrency as I have, the program runs considerably more slowly than when I am just returning values directly from the get_seq_len function. Am I implementing concurrency incorrectly? Or is the program just not complex enough that there is speed to be gained from concurrency or something?



    package main

    import ("fmt";"math";"time")


    This function takes a number x and then using the formula described in the above comment block creates a sequence of numbers from it until the number 1 is reached. Originally I had the function simply returning the length of the sequence, but now I have it sending the length to the specified channel.



    func get_seq_len(x int, c chan int) {
    var count int = 1
    for {
    if x == 1 {
    break
    } else if x%2 == 0 {
    x = x / 2
    } else {
    x = 3 * x + 1
    }
    count++
    }
    // return count + 1
    c <- count + 1
    }


    Here the main function just step through every number from 1 to whatever the max is and then tests the length of the sequence for that number. I use channel c to pass the sequenced length back to main().



    func main() {
    start := time.Now()
    var max int = int(math.Pow(10,6))
    // var max int = int(math.Pow(3,3))
    var max_length int = 0
    var max_num int = 0
    c := make(chan int, 50)

    for i:=1; i<max; i++ {
    // length := get_seq_len(i, c)
    go get_seq_len(i, c)
    length := <-c

    if length > max_length { max_length = length; max_num = i }
    }

    fmt.Println(max_num)
    t := time.Now()
    elapsed := t.Sub(start)
    fmt.Println(elapsed)

    }








    share









    $endgroup$















      0












      0








      0





      $begingroup$


      I am working through this problem on project euler.



      Basic purpose of the code:



      /*
      if n is even n -> n/2
      if n is odd n -> 3n + 1
      which starting number under 1 million produces the longest sequence?
      */


      The trouble with the code is that when I implement concurrency as I have, the program runs considerably more slowly than when I am just returning values directly from the get_seq_len function. Am I implementing concurrency incorrectly? Or is the program just not complex enough that there is speed to be gained from concurrency or something?



      package main

      import ("fmt";"math";"time")


      This function takes a number x and then using the formula described in the above comment block creates a sequence of numbers from it until the number 1 is reached. Originally I had the function simply returning the length of the sequence, but now I have it sending the length to the specified channel.



      func get_seq_len(x int, c chan int) {
      var count int = 1
      for {
      if x == 1 {
      break
      } else if x%2 == 0 {
      x = x / 2
      } else {
      x = 3 * x + 1
      }
      count++
      }
      // return count + 1
      c <- count + 1
      }


      Here the main function just step through every number from 1 to whatever the max is and then tests the length of the sequence for that number. I use channel c to pass the sequenced length back to main().



      func main() {
      start := time.Now()
      var max int = int(math.Pow(10,6))
      // var max int = int(math.Pow(3,3))
      var max_length int = 0
      var max_num int = 0
      c := make(chan int, 50)

      for i:=1; i<max; i++ {
      // length := get_seq_len(i, c)
      go get_seq_len(i, c)
      length := <-c

      if length > max_length { max_length = length; max_num = i }
      }

      fmt.Println(max_num)
      t := time.Now()
      elapsed := t.Sub(start)
      fmt.Println(elapsed)

      }








      share









      $endgroup$




      I am working through this problem on project euler.



      Basic purpose of the code:



      /*
      if n is even n -> n/2
      if n is odd n -> 3n + 1
      which starting number under 1 million produces the longest sequence?
      */


      The trouble with the code is that when I implement concurrency as I have, the program runs considerably more slowly than when I am just returning values directly from the get_seq_len function. Am I implementing concurrency incorrectly? Or is the program just not complex enough that there is speed to be gained from concurrency or something?



      package main

      import ("fmt";"math";"time")


      This function takes a number x and then using the formula described in the above comment block creates a sequence of numbers from it until the number 1 is reached. Originally I had the function simply returning the length of the sequence, but now I have it sending the length to the specified channel.



      func get_seq_len(x int, c chan int) {
      var count int = 1
      for {
      if x == 1 {
      break
      } else if x%2 == 0 {
      x = x / 2
      } else {
      x = 3 * x + 1
      }
      count++
      }
      // return count + 1
      c <- count + 1
      }


      Here the main function just step through every number from 1 to whatever the max is and then tests the length of the sequence for that number. I use channel c to pass the sequenced length back to main().



      func main() {
      start := time.Now()
      var max int = int(math.Pow(10,6))
      // var max int = int(math.Pow(3,3))
      var max_length int = 0
      var max_num int = 0
      c := make(chan int, 50)

      for i:=1; i<max; i++ {
      // length := get_seq_len(i, c)
      go get_seq_len(i, c)
      length := <-c

      if length > max_length { max_length = length; max_num = i }
      }

      fmt.Println(max_num)
      t := time.Now()
      elapsed := t.Sub(start)
      fmt.Println(elapsed)

      }






      go concurrency





      share












      share










      share



      share










      asked 3 mins ago









      The NightmanThe Nightman

      1947




      1947






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214889%2fconcurrency-slowing-down-go-code%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214889%2fconcurrency-slowing-down-go-code%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Fairchild Swearingen Metro Inhaltsverzeichnis Geschichte | Innenausstattung | Nutzung | Zwischenfälle...

          Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...

          Marineschifffahrtleitung Inhaltsverzeichnis Geschichte | Heutige Organisation der NATO | Nationale und...