
from time import time

class UseWrite:
    def __init__(self):
        self.out = open("/dev/null", "w")
    def nothing(self):
        pass
    def run(self):
        self.out.write("World!")

class UseWriteLong:
    def __init__(self):
        self.out = open("/dev/null", "w")
    def nothing(self):
        pass
    def run(self):
        self.out.write("Hello, World "+"b "+"c "+"d "+"Hello, World\n")

class UseWriteSeparate:
    def __init__(self):
        self.out = open("/dev/null", "w")
    def nothing(self):
        pass
    def run(self):
        self.out.write("Hello, World")
        self.out.write("b ")
        self.out.write("c ")
        self.out.write("d ")
        self.out.write("Hello, World\n")

class UsePrint:
    def __init__(self):
        self.out = open("/dev/null", "w")
    def nothing(self):
        pass
    def run(self):
        print >> self.out, "World!",

class UsePrintLong:
    def __init__(self):
        self.out = open("/dev/null", "w")
    def nothing(self):
        pass
    def run(self):
        print >> self.out, "Hello, World", "b", "c", "d", "Hello, World"

def bench(cls):
    """ Report the number of additional microseconds it took to execute
    cls.run() than it did to run cls.nothing().

    Measurement is done by running for about a half second and taking
    the average.  If it takes longer than that per run, it'll only be
    run once.
    """

    count = 1
    while True:
        (elapsed, answer) = bench_n(cls, count)
        if elapsed > 0.3:
            return answer
        count *= 4

def bench_n(cls, count):

    start = time()
    for x in xrange(1,count):
        cls.nothing()
    base = time() - start
    for x in xrange(1,count):
        cls.run()
    total = time() - start
    subject = total - base

    return ( total, 1000000 * subject/count )

print "write:", bench(UseWrite())
print "print", bench(UsePrint())
print "write long:", bench(UseWriteLong())
print "print long", bench(UsePrintLong())
print "write separate:", bench(UseWriteSeparate())
## conclusion -- the commas in print are actually kind of slow!
## well, only very slightly.    I guess out.write(...) is best.
## well, ...   eh, ... whatever.

