Module jobs
[hide private]
[frames] | no frames]

Source Code for Module jobs

 1  import random 
 2  from math import sqrt 
 3  from os import getpid 
 4  from time import sleep, strftime 
 5  from threading import currentThread 
 6  from itertools import count, ifilter 
 7   
 8  import papyros 
 9   
10   
11 -def log(msg):
12 print '%s PID=%d/%s:\t%s' % (strftime('%H:%M:%S'), getpid(), 13 currentThread().getName(), msg)
14 15
16 -class SlowSqrt(papyros.Job):
17 '''A non-CPU-intensive job: sleep for a few seconds and return the sqrt of 18 a number. 19 ''' 20
21 - def __str__(self):
22 return 'SlowSqrt(%s)' % self.args[0]
23
24 - def __call__(self, n):
25 t = random.randrange(1,5) 26 log('Pretending to work hard on computing sqrt(%s) for %d seconds' % (n,t)) 27 sleep(t) 28 return sqrt(n)
29 30
31 -class PrimeFactors(papyros.Job):
32 '''A CPU intensive job: compute the prime factors of a number.''' 33
34 - def __str__(self):
35 return 'PrimeFactors(%s)' % self.args[0]
36
37 - def __call__(self, n):
38 log('Factorizing %s' % n) 39 factors = [] 40 nextprime = sieve().next 41 candidate = nextprime() 42 thresh = sqrt(n) 43 while True: 44 if candidate > thresh: 45 factors.append(n) 46 break 47 d,m = divmod(n, candidate) 48 if m == 0: 49 factors.append(candidate) 50 n = d; thresh = sqrt(n) 51 else: 52 candidate = nextprime() 53 return factors
54 55
56 -def sieve():
57 # from Tim Hochberg's comment at 58 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117119 59 seq = count(2) 60 while True: 61 p = seq.next() 62 seq = ifilter(p.__rmod__, seq) 63 yield p
64