/*
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <devin at shiftedbits dot org> (Devin Lane) wrote this file. As long as you retain this notice you can do whatever you want with this stuff. 
 * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return.
 */

#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>

typedef void (*testerFunc)(CGContextRef c);

void testSetRGBFillColor(CGContextRef c)
{
	CGContextSetRGBFillColor(c, .5, .7, .4, .2);
	CGContextSetRGBFillColor(c, .8, .1, 0, 1);	
}

void testSetColor(CGContextRef c)
{
	static CGColorRef a = NULL, b = NULL;
	if (!a) {
		float compa[4] = {.5, .7, .4, .2};
		float compb[4] = {.8, .1, 0, 1};
		a = CGColorCreate(CGColorSpaceCreateDeviceRGB(), compa);
		b = CGColorCreate(CGColorSpaceCreateDeviceRGB(), compb);
	}
	
	CGContextSetFillColorWithColor(c, a);
	CGContextSetFillColorWithColor(c, b);
}

void testSetNSColor(CGContextRef c)
{
	static NSColor *a = nil, *b = nil;
	if (!a) {
		a = [[NSColor colorWithCalibratedRed:.5 green:.7 blue:.4 alpha:.2] retain];
		b = [[NSColor colorWithCalibratedRed:.8 green:.1 blue:0 alpha:1] retain];
	}
	
	[a setFill];
	[b setFill];
}

void testSetNSColorDynamic(CGContextRef c)
{
	[[NSColor colorWithCalibratedRed:.5 green:.7 blue:.4 alpha:.2] setFill];
	[[NSColor colorWithCalibratedRed:.8 green:.1 blue:0 alpha:1] setFill];
}

void tester(CGContextRef c, testerFunc t, NSString *desc)
{
	NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
	
	size_t iterations = 1000000;
	for (size_t i = 0; i < iterations; i++) {
		(*t)(c);		
	}
	
	NSLog(@"%@: %f seconds for %d iterations", desc, [NSDate timeIntervalSinceReferenceDate] - start, iterations);
}

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

	CGContextRef context = CGBitmapContextCreate(NULL, 10, 10, 8, 40, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedLast);
	
	tester(context, &testSetRGBFillColor, @"CGContextSetRGBFillColor");
	tester(context, &testSetColor, @"CGContextSetFillColorWithColor, static CGColorRef");
	[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO]];
	tester(context, &testSetNSColor, @"-[NSColor setFillColor], static NSColor");
	tester(context, &testSetNSColorDynamic, @"-[NSColor setFillColor], dynamic NSColor");
	
	CGContextRelease(context);
	
    [pool release];
    return 0;
}

