蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

测量分块统计、缓存命中和批量写入

PYTHONWindows、Python 3.12。各实验所需工具和版本见下载包 README。measure_stock.py
measure_stock.py134 行
"""Measure and verify streaming inventory statistics for local CSV inputs."""
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
from hashlib import file_digest
from itertools import islice
import json
import math
import os
from pathlib import Path
import sys
from tempfile import TemporaryDirectory
from threading import current_thread
from time import perf_counter

ALGORITHM = "stock-score-v1"


def chunk_rows(stream, size):
    import pandas as pd

    rows = valid = batches = 0
    total = 0.0
    if "score" not in pd.read_csv(stream, nrows=0).columns:
        raise ValueError("CSV needs a score column")
    stream.seek(0)
    with pd.read_csv(stream, chunksize=size, usecols=["score"], dtype={"score":"float64"}) as sections:
        for block in sections:
            count=len(block)
            if not count:
                continue
            series=block["score"]
            rows+=count
            valid+=int(series.count())
            total+=float(series.sum())
            batches+=1
    if not math.isfinite(total):
        raise ValueError("score total must be finite")
    return {"rows":rows,"valid":valid,"chunks":batches,"total":total,"mean":total/valid if valid else None}


def cached_result(path):
    if path is not None:
        try:
            data=json.loads(path.read_bytes())
            if set(data)=={"rows","valid","chunks","total","mean"}:
                return data
        except (OSError,ValueError,TypeError):
            pass
    return None


def stats(source, size, cache):
    started=perf_counter()
    with source.open("rb") as stream:
        before=os.fstat(stream.fileno())
        digest=file_digest(stream,"sha256").hexdigest()
        target=cache/f"{ALGORITHM}-{size}-{digest}.json" if cache else None
        data=cached_result(target)
        hit=data is not None
        if not hit:
            stream.seek(0)
            data=chunk_rows(stream,size)
        after=os.fstat(stream.fileno())
        if (before.st_size,before.st_mtime_ns)!=(after.st_size,after.st_mtime_ns):
            raise ValueError("input changed during reading")
    if not hit and target:
        target.parent.mkdir(parents=True,exist_ok=True)
        with TemporaryDirectory(prefix="writing-",dir=target.parent) as directory:
            candidate=Path(directory)/"stats.json"
            candidate.write_text(json.dumps(data,allow_nan=False),encoding="utf-8")
            candidate.replace(target)
    elapsed=perf_counter()-started
    return dict(data,cached=hit,digest=digest,seconds=elapsed,worker=current_thread().name)


def many(paths, size, workers):
    def run(path):
        try:
            return {"file":path.name,"ok":True,**stats(path,size,None)}
        except (OSError,ValueError) as error:
            return {"file":path.name,"ok":False,"error":type(error).__name__}
    if workers==1:
        return [run(path) for path in paths]
    ordered=[None]*len(paths)
    with ThreadPoolExecutor(max_workers=workers) as pool:
        futures={pool.submit(run,path):index for index,path in enumerate(paths)}
        for done in as_completed(futures):
            ordered[futures[done]]=done.result()
    return ordered


def write_lines(rows, sink, size):
    encoded=(json.dumps(row,ensure_ascii=False,allow_nan=False)+"\n" for row in rows)
    writes=0
    while group:=list(islice(encoded,size)):
        sink.write("".join(group))
        writes+=1
    return writes


def cli():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("files",type=Path,nargs="+")
    parser.add_argument("--chunks",type=int,default=10000)
    parser.add_argument("--workers",type=int,default=1)
    parser.add_argument("--cache",type=Path)
    parser.add_argument("--report",type=Path)
    parser.add_argument("--write-batch",type=int,default=200)
    args=parser.parse_args()
    if args.chunks<1 or args.workers<1 or args.write_batch<1:
        parser.error("choose positive chunk, worker and batch sizes")
    if args.cache and len(args.files)!=1:
        parser.error("select a single file for cache mode")
    paths=args.files
    imported_before="pandas" in sys.modules
    started=perf_counter()
    if args.cache:
        rows=[{"file":paths[0].name,"ok":True,**stats(paths[0],args.chunks,args.cache)}]
    else:
        rows=many(paths,args.chunks,args.workers)
    calls=None
    if args.report:
        if args.report.resolve() in {path.resolve() for path in paths}:
            parser.error("report must be a different file")
        with args.report.open("x",encoding="utf-8",newline="\n") as stream:
            calls=write_lines(rows,stream,args.write_batch)
    print(json.dumps({"rows":rows,"seconds":perf_counter()-started,"write_calls":calls,
                      "pandas_loaded_before":imported_before,"pandas_loaded_after":"pandas" in sys.modules},allow_nan=False))
    return 0 if all(row["ok"] for row in rows) else 2


if __name__=="__main__":
    raise SystemExit(cli())
本例需在 Windows、Python 3.12。各实验所需工具和版本见下载包 README。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。

入口文件:projects/skills-performance/measure_stock.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 measure_stock.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12。各实验所需工具和版本见下载包 README。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Skills(技能)

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a331.zip

下载课程关联工程包:Skills(技能)

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a346.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习