Ordered results with apply_async












0














I have read that the function apply_async doesn't give ordered results. If I have repeated calls to a function which prints the squares of a list of numbers, I can see from the display that the list is not ordered.



However when the function returns the number instead of printing it and I use .get() to get the values, then I see that the results are ordered.



I have a few questions --




  1. Why are the results from .get() ordered?

  2. If I have a loop which as a variable named a and its value is different for different iterations. Will using apply_async cause overwrites of the values of a as it runs the processes in parallel and asynchronously?

  3. Will I be able to save computational time if I run apply instead of apply_async? My code shows that apply is slower than the for loop. Why is that so?

  4. Can we use a function declared within the ___main___ function with apply_async?


Here is a small working example:



from multiprocessing import Pool
import time

def f(x):
return x*x

if __name__ == '__main__':

print('For loop')
t1f = time.time()
for ii in range(20):
f(ii)
t2f = time.time()
print('Time taken for For loop = ', t2f-t1f,' seconds')

pool = Pool(processes=4)
print('Apply async loop')
t1a = time.time()
results = [pool.apply_async(f, args = (j,)) for j in range(20)]

pool.close()
pool.join()
t2a = time.time()
print('Time taken for pool = ', t2a-t1a,' seconds')
print([results[hh].get() for hh in range(len(results))])


This results as:




For loop Time taken for For loop = 5.9604644775390625e-06 seconds



Apply async loop Time taken for pool = 0.10188460350036621 seconds



[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225,
256, 289, 324, 361]











share|improve this question





























    0














    I have read that the function apply_async doesn't give ordered results. If I have repeated calls to a function which prints the squares of a list of numbers, I can see from the display that the list is not ordered.



    However when the function returns the number instead of printing it and I use .get() to get the values, then I see that the results are ordered.



    I have a few questions --




    1. Why are the results from .get() ordered?

    2. If I have a loop which as a variable named a and its value is different for different iterations. Will using apply_async cause overwrites of the values of a as it runs the processes in parallel and asynchronously?

    3. Will I be able to save computational time if I run apply instead of apply_async? My code shows that apply is slower than the for loop. Why is that so?

    4. Can we use a function declared within the ___main___ function with apply_async?


    Here is a small working example:



    from multiprocessing import Pool
    import time

    def f(x):
    return x*x

    if __name__ == '__main__':

    print('For loop')
    t1f = time.time()
    for ii in range(20):
    f(ii)
    t2f = time.time()
    print('Time taken for For loop = ', t2f-t1f,' seconds')

    pool = Pool(processes=4)
    print('Apply async loop')
    t1a = time.time()
    results = [pool.apply_async(f, args = (j,)) for j in range(20)]

    pool.close()
    pool.join()
    t2a = time.time()
    print('Time taken for pool = ', t2a-t1a,' seconds')
    print([results[hh].get() for hh in range(len(results))])


    This results as:




    For loop Time taken for For loop = 5.9604644775390625e-06 seconds



    Apply async loop Time taken for pool = 0.10188460350036621 seconds



    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225,
    256, 289, 324, 361]











    share|improve this question



























      0












      0








      0







      I have read that the function apply_async doesn't give ordered results. If I have repeated calls to a function which prints the squares of a list of numbers, I can see from the display that the list is not ordered.



      However when the function returns the number instead of printing it and I use .get() to get the values, then I see that the results are ordered.



      I have a few questions --




      1. Why are the results from .get() ordered?

      2. If I have a loop which as a variable named a and its value is different for different iterations. Will using apply_async cause overwrites of the values of a as it runs the processes in parallel and asynchronously?

      3. Will I be able to save computational time if I run apply instead of apply_async? My code shows that apply is slower than the for loop. Why is that so?

      4. Can we use a function declared within the ___main___ function with apply_async?


      Here is a small working example:



      from multiprocessing import Pool
      import time

      def f(x):
      return x*x

      if __name__ == '__main__':

      print('For loop')
      t1f = time.time()
      for ii in range(20):
      f(ii)
      t2f = time.time()
      print('Time taken for For loop = ', t2f-t1f,' seconds')

      pool = Pool(processes=4)
      print('Apply async loop')
      t1a = time.time()
      results = [pool.apply_async(f, args = (j,)) for j in range(20)]

      pool.close()
      pool.join()
      t2a = time.time()
      print('Time taken for pool = ', t2a-t1a,' seconds')
      print([results[hh].get() for hh in range(len(results))])


      This results as:




      For loop Time taken for For loop = 5.9604644775390625e-06 seconds



      Apply async loop Time taken for pool = 0.10188460350036621 seconds



      [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225,
      256, 289, 324, 361]











      share|improve this question















      I have read that the function apply_async doesn't give ordered results. If I have repeated calls to a function which prints the squares of a list of numbers, I can see from the display that the list is not ordered.



      However when the function returns the number instead of printing it and I use .get() to get the values, then I see that the results are ordered.



      I have a few questions --




      1. Why are the results from .get() ordered?

      2. If I have a loop which as a variable named a and its value is different for different iterations. Will using apply_async cause overwrites of the values of a as it runs the processes in parallel and asynchronously?

      3. Will I be able to save computational time if I run apply instead of apply_async? My code shows that apply is slower than the for loop. Why is that so?

      4. Can we use a function declared within the ___main___ function with apply_async?


      Here is a small working example:



      from multiprocessing import Pool
      import time

      def f(x):
      return x*x

      if __name__ == '__main__':

      print('For loop')
      t1f = time.time()
      for ii in range(20):
      f(ii)
      t2f = time.time()
      print('Time taken for For loop = ', t2f-t1f,' seconds')

      pool = Pool(processes=4)
      print('Apply async loop')
      t1a = time.time()
      results = [pool.apply_async(f, args = (j,)) for j in range(20)]

      pool.close()
      pool.join()
      t2a = time.time()
      print('Time taken for pool = ', t2a-t1a,' seconds')
      print([results[hh].get() for hh in range(len(results))])


      This results as:




      For loop Time taken for For loop = 5.9604644775390625e-06 seconds



      Apply async loop Time taken for pool = 0.10188460350036621 seconds



      [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225,
      256, 289, 324, 361]








      python-3.x multiprocessing apply python-multiprocessing






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 7:15







      Shihab Khan

















      asked Nov 21 '18 at 7:08









      Shihab KhanShihab Khan

      227




      227
























          1 Answer
          1






          active

          oldest

          votes


















          3
















          1. Why are the results from .get() ordered?




          because the results list is ordered.





          1. If I have a loop which as a variable named a and its value is different for different iterations. Will using apply_async cause
            overwrites of the values of a as it runs the processes in parallel
            and asynchronously?




          generally no, but I can't tell without seeing the code.





          1. Will I be able to save computational time if I run apply instead of apply_async? My code shows that apply is slower than the for
            loop. Why is that so?




          no, apply blocks on each call, there is no parallelism. apply is slower because of multiprocessing overhead.





          1. Can we use a function declared within the ___main___ function with apply_async?




          yes for *nix, no for windows, because there is no fork().



          your time measurement of .apply_async is wrong, you should take t2a after result.get, and don't assume the result is finished in order:



          while not all(r.ready() for r in results):
          time.sleep(0.1)


          btw, your work function runs too fast to finish, do more computation to do a true benchmark.






          share|improve this answer























          • Thanks a lot George. Your answer helps a lot. So, it would be a good practice for me to use the .wait() function after apply_async and then .get() the results. Then I need not worry about the ordering?
            – Shihab Khan
            Nov 21 '18 at 13:29








          • 1




            @ShihabKhan in that case, why not use pool.map?
            – georgexsh
            Nov 21 '18 at 15:50










          • Thanks a lot. I was getting confused in the functions. I got a good link that explains the differences between them.
            – Shihab Khan
            Nov 22 '18 at 6:35











          Your Answer






          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: "1"
          };
          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: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          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%2fstackoverflow.com%2fquestions%2f53406895%2fordered-results-with-apply-async%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3
















          1. Why are the results from .get() ordered?




          because the results list is ordered.





          1. If I have a loop which as a variable named a and its value is different for different iterations. Will using apply_async cause
            overwrites of the values of a as it runs the processes in parallel
            and asynchronously?




          generally no, but I can't tell without seeing the code.





          1. Will I be able to save computational time if I run apply instead of apply_async? My code shows that apply is slower than the for
            loop. Why is that so?




          no, apply blocks on each call, there is no parallelism. apply is slower because of multiprocessing overhead.





          1. Can we use a function declared within the ___main___ function with apply_async?




          yes for *nix, no for windows, because there is no fork().



          your time measurement of .apply_async is wrong, you should take t2a after result.get, and don't assume the result is finished in order:



          while not all(r.ready() for r in results):
          time.sleep(0.1)


          btw, your work function runs too fast to finish, do more computation to do a true benchmark.






          share|improve this answer























          • Thanks a lot George. Your answer helps a lot. So, it would be a good practice for me to use the .wait() function after apply_async and then .get() the results. Then I need not worry about the ordering?
            – Shihab Khan
            Nov 21 '18 at 13:29








          • 1




            @ShihabKhan in that case, why not use pool.map?
            – georgexsh
            Nov 21 '18 at 15:50










          • Thanks a lot. I was getting confused in the functions. I got a good link that explains the differences between them.
            – Shihab Khan
            Nov 22 '18 at 6:35
















          3
















          1. Why are the results from .get() ordered?




          because the results list is ordered.





          1. If I have a loop which as a variable named a and its value is different for different iterations. Will using apply_async cause
            overwrites of the values of a as it runs the processes in parallel
            and asynchronously?




          generally no, but I can't tell without seeing the code.





          1. Will I be able to save computational time if I run apply instead of apply_async? My code shows that apply is slower than the for
            loop. Why is that so?




          no, apply blocks on each call, there is no parallelism. apply is slower because of multiprocessing overhead.





          1. Can we use a function declared within the ___main___ function with apply_async?




          yes for *nix, no for windows, because there is no fork().



          your time measurement of .apply_async is wrong, you should take t2a after result.get, and don't assume the result is finished in order:



          while not all(r.ready() for r in results):
          time.sleep(0.1)


          btw, your work function runs too fast to finish, do more computation to do a true benchmark.






          share|improve this answer























          • Thanks a lot George. Your answer helps a lot. So, it would be a good practice for me to use the .wait() function after apply_async and then .get() the results. Then I need not worry about the ordering?
            – Shihab Khan
            Nov 21 '18 at 13:29








          • 1




            @ShihabKhan in that case, why not use pool.map?
            – georgexsh
            Nov 21 '18 at 15:50










          • Thanks a lot. I was getting confused in the functions. I got a good link that explains the differences between them.
            – Shihab Khan
            Nov 22 '18 at 6:35














          3












          3








          3








          1. Why are the results from .get() ordered?




          because the results list is ordered.





          1. If I have a loop which as a variable named a and its value is different for different iterations. Will using apply_async cause
            overwrites of the values of a as it runs the processes in parallel
            and asynchronously?




          generally no, but I can't tell without seeing the code.





          1. Will I be able to save computational time if I run apply instead of apply_async? My code shows that apply is slower than the for
            loop. Why is that so?




          no, apply blocks on each call, there is no parallelism. apply is slower because of multiprocessing overhead.





          1. Can we use a function declared within the ___main___ function with apply_async?




          yes for *nix, no for windows, because there is no fork().



          your time measurement of .apply_async is wrong, you should take t2a after result.get, and don't assume the result is finished in order:



          while not all(r.ready() for r in results):
          time.sleep(0.1)


          btw, your work function runs too fast to finish, do more computation to do a true benchmark.






          share|improve this answer
















          1. Why are the results from .get() ordered?




          because the results list is ordered.





          1. If I have a loop which as a variable named a and its value is different for different iterations. Will using apply_async cause
            overwrites of the values of a as it runs the processes in parallel
            and asynchronously?




          generally no, but I can't tell without seeing the code.





          1. Will I be able to save computational time if I run apply instead of apply_async? My code shows that apply is slower than the for
            loop. Why is that so?




          no, apply blocks on each call, there is no parallelism. apply is slower because of multiprocessing overhead.





          1. Can we use a function declared within the ___main___ function with apply_async?




          yes for *nix, no for windows, because there is no fork().



          your time measurement of .apply_async is wrong, you should take t2a after result.get, and don't assume the result is finished in order:



          while not all(r.ready() for r in results):
          time.sleep(0.1)


          btw, your work function runs too fast to finish, do more computation to do a true benchmark.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 '18 at 10:34

























          answered Nov 21 '18 at 10:26









          georgexshgeorgexsh

          10.1k11136




          10.1k11136












          • Thanks a lot George. Your answer helps a lot. So, it would be a good practice for me to use the .wait() function after apply_async and then .get() the results. Then I need not worry about the ordering?
            – Shihab Khan
            Nov 21 '18 at 13:29








          • 1




            @ShihabKhan in that case, why not use pool.map?
            – georgexsh
            Nov 21 '18 at 15:50










          • Thanks a lot. I was getting confused in the functions. I got a good link that explains the differences between them.
            – Shihab Khan
            Nov 22 '18 at 6:35


















          • Thanks a lot George. Your answer helps a lot. So, it would be a good practice for me to use the .wait() function after apply_async and then .get() the results. Then I need not worry about the ordering?
            – Shihab Khan
            Nov 21 '18 at 13:29








          • 1




            @ShihabKhan in that case, why not use pool.map?
            – georgexsh
            Nov 21 '18 at 15:50










          • Thanks a lot. I was getting confused in the functions. I got a good link that explains the differences between them.
            – Shihab Khan
            Nov 22 '18 at 6:35
















          Thanks a lot George. Your answer helps a lot. So, it would be a good practice for me to use the .wait() function after apply_async and then .get() the results. Then I need not worry about the ordering?
          – Shihab Khan
          Nov 21 '18 at 13:29






          Thanks a lot George. Your answer helps a lot. So, it would be a good practice for me to use the .wait() function after apply_async and then .get() the results. Then I need not worry about the ordering?
          – Shihab Khan
          Nov 21 '18 at 13:29






          1




          1




          @ShihabKhan in that case, why not use pool.map?
          – georgexsh
          Nov 21 '18 at 15:50




          @ShihabKhan in that case, why not use pool.map?
          – georgexsh
          Nov 21 '18 at 15:50












          Thanks a lot. I was getting confused in the functions. I got a good link that explains the differences between them.
          – Shihab Khan
          Nov 22 '18 at 6:35




          Thanks a lot. I was getting confused in the functions. I got a good link that explains the differences between them.
          – Shihab Khan
          Nov 22 '18 at 6:35


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • 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.


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





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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.


          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%2fstackoverflow.com%2fquestions%2f53406895%2fordered-results-with-apply-async%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

          Costa Masnaga

          Fotorealismo

          Sidney Franklin