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

slower than loop? #84

Open
nickhuangxinyu opened this issue May 23, 2021 · 3 comments
Open

slower than loop? #84

nickhuangxinyu opened this issue May 23, 2021 · 3 comments

Comments

@nickhuangxinyu
Copy link

I test the threadpool with this code:

#include "util/time_util.h"
#include "ThreadPool/ThreadPool.h"

size_t i = 0;
void test() {
  // printf("hah\n");
  i++;
  i++;
}

#define N 1000000
void fun1() {
  printf("func1\n");
  ThreadPool pool(10);
  for (int i = 0; i < N; ++i) {
    pool.enqueue(test);
  }
}

void fun2() {
  printf("func2\n");
  for (int i = 0; i < N; ++i) {
    test();
  }
}

int main(int argc, char** argv) {
  util::time_util::Timer t;
  t.StartTimer();
  if (argc == 1) {
    fun1();
  } else {
    fun2();
  }
  printf("i=%d\n", i); 
  t.EndTimer("1");
}

I found thread pool cost 5s, but loop just cost 0.005s

why threadpool not speed up?

@wilx
Copy link
Contributor

wilx commented May 23, 2021

You have basically re-discovered Amdalh's law. Creating the threads and maintaining the queue costs time and the code you execute in the threads is very short. Also, it probably synchronizes on the output as well.

@Zzzzzya
Copy link

Zzzzzya commented Oct 30, 2023

Creating a thread does not mean that dealing with tasks will be fast. u create a pool with 10 threads. creating thread is quiet more expensive than u think. That's exactly why we need threadpool , avoiding create and destroy threads too many times

@kadbbs
Copy link

kadbbs commented Feb 19, 2024

Your task is too small

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants