simple thread benchmark

SK sk at metrokings.com
Tue Aug 17 20:43:59 PDT 2010


Hi,
This is my first D program.  It benchmarks fiber vs. thread context
switching time.  I attached a graph of some results if you're curious.

I don't know if this list is appropriate for code review.  If so, I
would very much appreciate a critique.  I suspect I'm missing some out
on a few nice D'isms that would improve this little guy.
Thank you!
-steve


import std.stdio;
import core.thread;
import std.perf;

immutable uint yield_count = 100000;

uint stack_check()
{
	uint x;
	asm
	{
		mov x,ESP;
	}
	return x;
}

void fiber_func()
{
	uint i = yield_count;
	while( --i ) Fiber.yield();
}

void thread_func()
{
	uint i = yield_count;
	while( --i ) Thread.yield();
}

ulong fiber_test( const uint worker_count )
{
	Fiber[] fib_array = new Fiber[worker_count];

	foreach( ref f; fib_array )
		f = new Fiber( &fiber_func );

	auto timer = new PerformanceCounter;

	uint i = yield_count;

	// fibers are cooperative and need a driver loop
	timer.start();
	bool done;
	do
	{	
		done = true;
		foreach( f; fib_array )
		{
			f.call();
			if( f.state() != f.State.TERM )
				done = false;
		}
	} while( !done );
	timer.stop();
	return timer.milliseconds();
}

ulong thread_test( const uint worker_count )
{
	Thread[] thread_array = new Thread[worker_count];

	foreach( ref t; thread_array )
		t = new Thread( &thread_func );

	auto timer = new PerformanceCounter;
	timer.start();
	foreach( t; thread_array )
		t.start();
	thread_joinAll();
	timer.stop();
	return timer.milliseconds();
}

int main()
{
	writeln( "worker_count, yield_count, fiber(ms), thread(ms)" );
	for( uint worker_count = 0; worker_count < 20; ++worker_count )
	{
		auto fib_ms = fiber_test( worker_count );
		auto thd_ms = thread_test( worker_count );
		writeln(  worker_count, ", ", yield_count, ",", fib_ms, ", ", thd_ms );
	}
	return 0;
}
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D context switch rate small.jpg
Type: image/jpeg
Size: 59293 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20100817/4820430f/attachment-0001.jpg>


More information about the Digitalmars-d-learn mailing list