You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

斐波那契数列生成中相邻n值计算时间差异显著的原因及解决方案咨询

斐波那契数列生成中相邻n值计算时间差异显著的原因及解决方案咨询

每个方法的计算时间都存在很大差异,即使进行了多次重复测试(取平均值)也是如此。而且随着n值增大,这种差异似乎变得更加明显。

Results graph (25 repeats)

这是我的计时代码:

def timeBlock(func, n, rep):
    start = time.perf_counter()
    for i in range(rep):
        func(n)
    end = time.perf_counter()
    return (end - start)/rep

def worker(args):
    func, n, rep = args
    try:
        elapsed = timeBlock(func, n, rep)
        return n, elapsed, None
    except Exception as e:
        return n, float("inf"), traceback.format_exc()

def trackFuncs(funcs):
    results = {name: [] for name in funcs.keys()}
    numProcesses = max(1, cpu_count() - 1)
    pool = Pool(processes=numProcesses)    
    try:
        for name, func in funcs.items():
            n = 0
            progressBar = tqdm(desc=f"Tracking {name}", unit="", dynamic_ncols=True)
            while True:
                tasks = [(func, n + i, REPEATS) for i in range(numProcesses)]
                try:
                    asyncResults = pool.imap_unordered(worker, tasks)
                    for result in asyncResults:
                        n, elapsed, error = result
                        if error:
                            print(f"Error for {name} at n={n}:\n{error}")
                            continue
                        results[name].append((n, elapsed))
                        if elapsed > MAXT:
                            progressBar.close()
                            print(f"Reached {MAXT}s for {name} at n={n}")
                            raise StopIteration
                except StopIteration:
                    break
                n += numProcesses
                progressBar.update(numProcesses)
            progressBar.close()
    except KeyboardInterrupt:
        print("\nProcess interrupted by user")
    finally:
        pool.close()
        pool.terminate()
        pool.join()
    return results

trackFuncs中的funcs是一个斐波那契函数的字典,键为函数名称。

图表图例中的函数本应大致按速度排序,但由于计算时间出现大幅峰值超过阈值,结果并不总是符合预期。

我尝试过对每个n值重复测试并取平均值,但随着重复次数增加,这种差异问题似乎反而更严重了。

有没有人知道这是什么原因导致的?如果可以的话,该如何解决这个问题?

备注:内容来源于stack exchange,提问作者Lockyli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 15:29:30