Home > other >  why each thread run time is different
why each thread run time is different

Time:07-03

I create an array with 1000000 element and each element is random, I have two question

  • Why each thread run time is different and every time I run code time is different ? What does the running time of thread depend on ?
  • Why Sequential is faster than Multithread ?

Thank you very much

def Result(arr,n):
   sum = 0
   for i in arr: sum  = i
   arr_list[n] = sum

def Thread_func(number):
   arr_thread = []
   start = perf_counter()

   for i in range(number):
      head = int(i*1000000/number)
      tail = int((i 1)*1000000/number)
      thread = threading.Thread(target=Result, args=(randnums[head:tail],i))
      arr_thread.append(thread)
      thread.start()

   for thread in arr_thread:
      thread.join()

   end = perf_counter()

   print('Multithread with {} threads fishined in {} s'.format(number, end - start))
random_arr = [random.choice(range(1000000)) for _ in range(1000000)]
arr = [2,3,4,5,6,7,8,9,10]
arr_list = list(range(max(arr)))
for i in arr:
    Thread_func(i)

enter image description here

CodePudding user response:

Why each thread run time is different and every time I run code time is different ? What does the running time of thread depend on ?

There are a lot of processes running on your system. The runtime of anything on your system is influenced by the kernel's ability to schedule it, which depends on the activity of everything else on the system. The only way to get consistent runtimes is using some sort of realtime kernel (or embedded devices that don't run multiple processes).

Why Sequential is faster than Multithread ?

Using multiple threads will seldom give you a performance advantage for CPU-intensive tasks. Due to the design of Python, only one thread is ever actually executing at the same time. Threads are most useful when you are trying to parallelize IO-bound operations (e.g., fetching data over the network).

For CPU-intensive operations, the multiprocessing module is often a better choice (because this spawns multiple independent instances of the Python interpreter and can take advantage of multiple CPUs), but the overhead involved in setting up and tearing down the processes make the solution no better (or even worse) than the single process version depending on your workload.

  • Related