1


这是编程之美这本书里的一道题目。我这里给出我修改的C语言版本。目的是找高手优化代码。给出更精简或者更易读或者更合理的代码。

int main() 
{ 
    //如果是双核请不要把这一句注释掉  
    //SetProcessAffinityMask(GetCurrentProcess(),0x1); 
    const double STEP=0.01,PI=3.14159265359; 
    const int INTERVAL=100; 
    double x=0.0; 
    DWORD busy,idle,startTime; 
    while(true) 
    { 
        busy=(DWORD)(INTERVAL*.5*(sin(PI*x)+1)); 
        idle=INTERVAL-busy; 
        startTime=GetTickCount(); 
        while((GetTickCount()-startTime)<=busy) 
            ; 
        Sleep(idle); 
        x+=STEP;         
    }    
    return 0; 
}
垃圾帖?
提问于2009-02-15 16:47:33
120 1 5
评论 (1)
1


Python版本的实现:

#!/usr/bin/env python
import itertools, math, time, sys

time_period = float(sys.argv[1]) if len(sys.argv) > 1 else 30   # seconds
time_slice  = float(sys.argv[2]) if len(sys.argv) > 2 else 0.04 # seconds

N = int(time_period / time_slice)
for i in itertools.cycle(range(N)):
    busy_time = time_slice / 2 * (math.sin(2*math.pi*i/N) + 1)
    t = time.clock() + busy_time
    while t > time.clock():
        pass
    time.sleep(time_slice - busy_time);

作者:J.F. Sebastian

永久链接 | 垃圾帖?
回答于2009-02-16 18:50:00
348 2 10
添加评论




Made with Django.

当前版本: R-0127-20090523

cc-wiki