Kenneth P. Turvey wrote On 10/06/05 15:40,:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
OK, it seems there are two ways to get the number of processors, one in
Runtime and the other in OperatingSystemMXBean, but there is now way to
get a hint on how many threads are optimal. It's too bad. That's what
you really want from the operating system, not how many CPUs it has.
The processor count can be misleading on systems where
some kind of resource management is running -- just because
a CPU is present and idle doesn't mean the system will
necessarily let you have it. There's also the issue of
dynamic reconfiguration, where CPUs can be added to and
removed from "domains" or "partitions" while programs are
running. Still, CPU count is a reasonable default, provided
you offer a way for the user to override it with his superior
knowledge.
The Holy Grail would be some kind of self-adjusting
scheme. For long-running CPU-bound programs such a scheme
might actually work (I confess I haven't tried it). The
idea would be to start a small number of threads, let them
run for a while, and measure the amount of progress they make
per unit time. Then add a few more threads, let the whole
bunch run a little longer, and measure again. If the rate
of progress has improved in approximate proportion to the
increase in thread count, adding those threads was a step in
the right direction and you can try adding a few more. If
progress has improved less than expected (e.g., going from
ten to eleven threads gave only a 2% boost), or if the progress
actually slowed down, you're running too many threads and
should get rid of a few of them.
Of course, not every CPU-bound program is easy to organize
in this manner. The individual "atoms" of work may be too
coarse-grained to permit easy "progress" measurement, the
overall task may not run long enough for the process to converge
on a good thread count, the problem structure may require that
the number of threads be known in advance, and so on. Still,
for some classes of program I think the approach might work.
If you decide to try it, I'd like to hear about your experiences.