-2
from multiprocessing.dummy import Pool as ThreadPool
import time
def f(x):
    val=x
    for i in xrange(100000):
        if i!=0:
            val*=i
            val%=10000
    return x
start = time.time()
iter=10000
pool=ThreadPool(8)
res=pool.map(f,xrange(100))
pool.close()
pool.join()
pool=ThreadPool(8)
res2=pool.map(f,xrange(100))
pool.close()
pool.join()
print "Elapsed Time: %s" % (time.time() - start)

above is the multithread code,when run in my 8 core computer,it takes 14s

from multiprocessing.dummy import Pool as ThreadPool
import time
def f(x):
    val=x
    for i in xrange(100000):
        if i!=0:
            val*=i
            val%=10000
    return x
start = time.time()
iter=10000
for i in xrange(100):
    f(i)
for i in xrange(100):
    f(i)
print "Elapsed Time: %s" % (time.time() - start)

above is the single thread code,it takes 7s can anyone explain it to me? thanks

Rong
  • 11
  • 2

2 Answers2

0

I got a similar results:

Elapsed Time: 4.83800005913 for the first code 
Elapsed Time: 2.95100021362 for the second code

your code is just compute something, which is not the forte of multithread, if you want to use multithread, take the IO busy job such as file or network, but not just compute something.

lqhcpsgbl
  • 3,694
  • 3
  • 21
  • 30
-1

As stated in this post, you can't do parallel execution with multiprocessing.dummy.

Community
  • 1
  • 1
ElderBug
  • 5,926
  • 16
  • 25