fix(m0): judge game frames by what the screen showed and drop spoilt windows

- Frame rate, 1 % low and hitches come from msBetweenDisplayChange of the
  frames that reached the screen; frames never shown are counted apart and
  the presented rate is kept as presented_fps. A game presenting 60 fps
  while the screen changes every 167 ms now shows as the stutter it is.
- A window whose capture failed, a busy window where the LLM finished no
  answer, and every busy window when the STT load failed are not counted.
- A yielding window counts only when every Jarvis process got both its
  CPU and its GPU priority lowered.
- The "game hardly drawing" floor applies only with Jarvis off or idle, so
  a game Jarvis slows that far still counts as harm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 09:12:15 +09:00
parent dff18c5c7e
commit cec52165b2
4 changed files with 116 additions and 39 deletions

View File

@@ -37,7 +37,7 @@
- **첫 실행 자가 점검**: 설치가 끝나면 평소·게임 중 배치로 각각 30초씩 출력 속도와 음성 첫 문장 시간을 잽니다. 평소 배치가 기준(출력 30 tok/s, 음성 첫 문장 0.7초)에 못 미치는 PC는 평소에도 동시 요청 1개, 이미지 CPU 읽기, 지난 대화 약 4천 토큰으로 시작합니다. 게임 중 배치가 기준에 못 미치면 대시보드와 설정 화면에 "게임 중에는 답이 느릴 수 있음"을 표시합니다.
- **GPU 사용률 제한은 두지 않습니다**: Jarvis 옆에서 보는 영상이 끊기지 않도록 LLM 엔진과 음성·두뇌 워커를 200ms마다 함께 10ms씩 멈추는 제한(Windows 프로세스 일시정지)을 검토했지만 뺐습니다(2026-11-11). M0 `gamemode_tune`에서는 멈춘 시간이 정한 대로 5.2%였는데도 nvidia-smi 사용률이 내려가지 않았고(STT를 쉬지 않고 돌릴 때 중앙값 96→98%, LLM만 40→39%) 출력만 6~10% 느려졌습니다([측정 결과](#자동-조절-측정-m0-gamemode_tune-2026-11-11)). M0 `video_drops`에서는 제한이 없어도 Jarvis가 GPU를 98%까지 쓰는 동안 유튜브 1080p 60fps 영상이 끊기지 않았고, 95% 제한은 끊긴 프레임을 줄이지 못했습니다([측정 결과](#영상-끊김-측정-m0-video_drops-2026-11-11)). 미리 정한 기준(제한이 끊김을 줄이지 못하면 설정을 뺌)대로 설정에서 뺐습니다. 게임 화면 프레임에 주는 영향은 아래 `game_frames`로 따로 잽니다.
- **대신 게임 화면의 프레임을 직접 보고, 멈추는 대신 우선순위로 양보합니다(후보, M0 `game_frames`로 정함)**: 사용률 제한은 GPU 전체 사용률을 보고 Jarvis를 일정 시간씩 멈추는 방식이라, 게임이 GPU를 원하지 않을 때도 Jarvis를 느리게 했고 정작 막으려던 것(화면이 끊기는 것)은 보지 않았습니다. 그래서 두 가지를 바꿉니다(2026-11-11).
- **기준은 게임 화면의 프레임 시간입니다**: 평균 fps, 1% low(가장 느린 1% 프레임), 50ms·100ms를 넘는 프레임 수를 봅니다. Windows가 기록하는 "게임이 프레임을 내보낸 시각"만 읽고 게임 화면은 보지 않습니다.
- **기준은 게임 화면의 프레임 시간입니다**: 평균 fps, 1% low(가장 느린 1% 프레임), 50ms·100ms를 넘는 프레임 수를 봅니다. 게임이 프레임을 만든 간격이 아니라 화면이 실제로 바뀐 간격으로 셉니다. 게임은 60fps로 프레임을 내도 화면에는 일부만 나갈 수 있기 때문입니다. 화면에 나가지 못한 프레임 수도 따로 셉니다. Windows가 기록하는 프레임 시각만 읽고 게임 화면은 보지 않습니다.
- **양보(후보)**: 게임 중에는 LLM 엔진과 음성·두뇌 워커의 CPU 우선순위와 GPU 스케줄링 우선순위를 "보통 이하"로 둡니다(Windows 프로세스 우선순위, 일시정지 없음). Windows는 게임이 같은 코어나 GPU를 원할 때만 게임에 먼저 내주므로, 게임이 덜 바쁠 때는 Jarvis 속도가 그대로입니다. 게임이 없을 때는 양보하지 않습니다(영상은 양보 없이도 끊기지 않았음). 설정 화면에는 두지 않습니다.
- **미리 정한 기준**: Jarvis가 답하는 동안 게임의 평균 fps와 1% low가 게임만 켠 때보다 5% 넘게 떨어지지 않고 50ms 넘는 프레임도 늘지 않으면, 아무것도 더하지 않습니다(양보도 넣지 않음). 더 떨어지면 양보가 그 하락을 절반 이상 줄일 때 게임 중 기본으로 켭니다. 이때 Jarvis 출력이 20% 넘게 느려지면 켜기 전에 사용자에게 묻습니다. 양보로도 줄지 않으면 넣지 않고, 대시보드에서 게임 중 일시정지를 안내합니다.
- **실행 중 감시**: 대시보드가 이미 재는 단계별 지연을 씁니다. 음성 첫 문장이 최근 5번 중 3번 이상 0.7초를 넘으면 다시 시작 없이 바꿀 수 있는 것부터 낮춥니다: 지난 대화 양 → 화질 → 캡처 미리 준비. 10분 동안 기준 안에 들면 하나씩 되돌립니다. 다시 시작이 필요한 배치 변경은 게임 감지와 VRAM 부족 때만 합니다.
@@ -159,7 +159,7 @@ LLM과 STT를 함께 켠 측정(M0 `gamemode_stt`, 게임 없음). STT를 먼저
### 게임 프레임 측정 (M0 `game_frames`, 측정 전)
게임을 켜고 캐릭터를 한자리에 세워 둔 채로 창마다 1분씩 잽니다. 순서는 게임만 → Jarvis를 켜 두고 쉼 → Jarvis 바쁨 → 바쁨+양보 → 바쁨+양보 → 바쁨 → 다시 게임만입니다(바쁨 줄은 A B B A 순서라 천천히 바뀌는 장면 탓이 한쪽에만 쌓이지 않음). Jarvis는 게임 중 배치(전문가 2GB, 맥락 16K, 음성 인식 GPU)이고, "바쁨"은 LLM이 쉬지 않고 답하고 음성 인식이 정한 대로 최종 전사만 하는 상태입니다. 프레임 시간은 PresentMon(인텔의 공개 도구, 버전과 해시 고정)으로 게임 프로세스 하나만 기록하고, 게임 이름이 든 원본 기록은 읽자마자 지웁니다. Windows 이벤트 기록을 쓰므로 관리자 권한이 필요하고, 게임을 켜기 전에 한 번만 묻습니다. 양보 창에서는 우선순위가 실제로 낮아졌는지 다시 읽어서 확인하고, 낮아지지 않았으면 비교에서 뺍니다.
게임을 켜고 캐릭터를 한자리에 세워 둔 채로 창마다 1분씩 잽니다. 순서는 게임만 → Jarvis를 켜 두고 쉼 → Jarvis 바쁨 → 바쁨+양보 → 바쁨+양보 → 바쁨 → 다시 게임만입니다(바쁨 줄은 A B B A 순서라 천천히 바뀌는 장면 탓이 한쪽에만 쌓이지 않음). Jarvis는 게임 중 배치(전문가 2GB, 맥락 16K, 음성 인식 GPU)이고, "바쁨"은 LLM이 쉬지 않고 답하고 음성 인식이 정한 대로 최종 전사만 하는 상태입니다. 프레임 시간은 PresentMon(인텔의 공개 도구, 버전과 해시 고정)으로 게임 프로세스 하나만 기록하고, 게임 이름이 든 원본 기록은 읽자마자 지웁니다. Windows 이벤트 기록을 쓰므로 관리자 권한이 필요하고, 게임을 켜기 전에 한 번만 묻습니다. 프레임 수와 간격은 화면이 실제로 바뀐 시각으로 셉니다. 양보 창에서는 Jarvis 프로세스 모두의 CPU·GPU 우선순위가 실제로 낮아졌는지 다시 읽어서 확인하고, 하나라도 낮아지지 않았으면 그 창을 비교에서 뺍니다. 프레임 기록이 실패하거나 중간에 끊긴 창, LLM이 답을 하나도 끝내지 못한 바쁨 창, 음성 인식 부하가 실패한 바쁨 창도 뺍니다. 게임이 거의 그려지지 않은 창(1초에 5프레임 미만)은 Jarvis가 꺼져 있거나 쉴 때만 뺍니다. Jarvis가 바쁠 때 그렇게 떨어지면 그것이 바로 재려는 피해이기 때문입니다.
## 화면 보기: 전체 화면, 모니터별, 프로그램(창)별

View File

@@ -49,7 +49,7 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰
- 게임 감지는 실행 중인 프로그램 이름과 창 모양만 봅니다. 게임 화면은 저장하지 않습니다. 설치된 게임은 이름과 안티치트 유무만 기록합니다.
- 음성 테스트는 키트에 들어 있는 합성 음성만 씁니다. 마이크는 쓰지 않습니다.
- 영상 끊김 단계(`video_drops`)는 유튜브에 공개된 Blender 영상을 새 임시 브라우저 프로필로 엽니다. 로그인하지 않고, 평소 쓰시는 프로필은 건드리지 않으며, 끝나면 그 임시 프로필을 지웁니다. 저장하는 것은 영상의 프레임 수, 끊긴 프레임 수, 화질, 광고가 나왔는지뿐입니다.
- 게임 프레임 단계(`game_frames`)는 PresentMon(인텔의 공개 도구)으로 게임이 프레임을 내보낸 시각만 기록합니다. 게임 화면은 보지 않고, 게임 이름이 든 원본 기록은 읽자마자 지웁니다. 저장하는 것은 fps, 1% low, 긴 프레임 수 같은 숫자뿐입니다.
- 게임 프레임 단계(`game_frames`)는 PresentMon(인텔의 공개 도구)으로 게임이 프레임을 내보낸 시각과 그 프레임이 화면에 나간 시각만 기록합니다. 게임 화면은 보지 않고, 게임 이름이 든 원본 기록은 읽자마자 지웁니다. 저장하는 것은 fps, 1% low, 긴 프레임 수 같은 숫자뿐입니다.
- PC 제어 도구 단계는 다른 프로그램의 창 제목과 화면 글자를 저장하지 않습니다. 개수, 걸린 시간, 오류 코드, 계산기 결과 숫자만 저장합니다. 이미 켜 둔 계산기가 있으면 건드리지 않고 그 확인을 건너뛰며, 브라우저는 평소 쓰시는 프로필이 아닌 새 임시 프로필로 엽니다.
## 옵션 (PowerShell에서 직접 실행할 때)
@@ -78,6 +78,6 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰
`run_m0_video.bat`을 더블클릭하면 Jarvis 옆에서 보는 영상이 끊기는지 잽니다(`video_drops`). 크롬(없으면 엣지)이 새 임시 프로필로 떠서 유튜브의 Blender 영상(Big Buck Bunny, 1080p 60fps, 소리 끔)을 틉니다. 광고가 나오면 건너뛸 수 있을 때 건너뛰고 끝날 때까지 기다립니다. 영상을 틀어 둔 채로 (1) Jarvis를 끈 상태 1분, (2) LLM(평소 배치, STT 자리와 여유 1GB)과 STT를 켜 두고 쉬는 상태 1분, (3) LLM이 답하고 STT가 10명 동시 전사를 쉬지 않고 하는 상태를 GPU 95% 제한 없이 두 번, 제한을 켜고 두 번, (4) 다시 Jarvis를 끈 상태 1분을 잽니다. 각각 끊긴 프레임 수(유튜브 "전문가용 통계"의 Dropped Frames와 같은 값)와, 화면에 프레임이 50ms·100ms 넘게 안 바뀐 횟수를 셉니다. 10~15분 걸립니다. 그동안 브라우저 창을 가리거나 최소화하지 말고 PC에 손대지 않으시면 됩니다. 광고, 일시정지, 버퍼링, 건너뛰기가 끼었거나 화질이 1080p 60fps가 아니었던 구간, 제한을 켰는데 Jarvis를 실제로 멈추지 못한 구간은 기록만 하고 비교에서는 뺍니다. 영상이 멈추거나 유튜브 오류가 뜨거나 페이지가 새로고침되면 키트가 알아서 다시 틀고(재생을 누르고, 안 되면 페이지를 다시 엽니다) 그 구간을 최대 3번까지 다시 잽니다. 직접 새로고침하지 않으셔도 됩니다. 화질이나 프레임 수가 떨어진 구간은 GPU 탓일 수 있어서 다시 재지 않습니다.
`run_m0_game_frames.bat`을 더블클릭하면 Jarvis가 게임 화면을 끊기게 하는지 잽니다(`game_frames`). 게임 프레임은 Windows 이벤트 기록으로 재므로 처음에 관리자 권한을 묻는 창이 한 번 뜹니다. 게임을 켜기 전에 "예"를 눌러 주세요. 그다음 게임을 켜고 플레이 화면까지 들어간 뒤 Enter를 누르고 15초 안에 게임으로 돌아가면 됩니다. 끝날 때까지 캐릭터를 한자리에 세워 두고 마우스·키보드에 손대지 마세요. 창마다 1분씩 (1) 게임만, (2) Jarvis(게임 중 배치)를 켜 두고 쉴 때, (3) LLM이 답하고 음성 인식이 최종 전사를 하는 동안을 그냥 두 번, Jarvis의 CPU·GPU 우선순위를 낮춰 게임에 양보하게 하고 두 번, (4) 다시 게임만 잽니다. 10~15분 걸리고 끝나면 알림음이 울립니다. 게임이 앞에 없었던 구간, 게임이 프레임을 거의 내지 않은 구간, 우선순위가 실제로 낮아지지 않은 양보 구간은 기록만 하고 비교에서 뺍니다. 프레임 제한(수직 동기화나 fps 제한)은 평소 쓰시는 대로 두셔도 됩니다.
`run_m0_game_frames.bat`을 더블클릭하면 Jarvis가 게임 화면을 끊기게 하는지 잽니다(`game_frames`). 게임 프레임은 Windows 이벤트 기록으로 재므로 처음에 관리자 권한을 묻는 창이 한 번 뜹니다. 게임을 켜기 전에 "예"를 눌러 주세요. 그다음 게임을 켜고 플레이 화면까지 들어간 뒤 Enter를 누르고 15초 안에 게임으로 돌아가면 됩니다. 끝날 때까지 캐릭터를 한자리에 세워 두고 마우스·키보드에 손대지 마세요. 창마다 1분씩 (1) 게임만, (2) Jarvis(게임 중 배치)를 켜 두고 쉴 때, (3) LLM이 답하고 음성 인식이 최종 전사를 하는 동안을 그냥 두 번, Jarvis의 CPU·GPU 우선순위를 낮춰 게임에 양보하게 하고 두 번, (4) 다시 게임만 잽니다. 10~15분 걸리고 끝나면 알림음이 울립니다. fps와 긴 프레임은 화면이 실제로 바뀐 간격으로 셉니다. 게임이 앞에 없었던 구간, 프레임 기록이 실패한 구간, Jarvis를 끄거나 쉬게 둔 동안 게임이 프레임을 거의 내지 않은 구간, LLM이나 음성 인식 부하가 제대로 돌지 않은 바쁨 구간, Jarvis 프로세스 하나라도 우선순위가 낮아지지 않은 양보 구간은 기록만 하고 비교에서 뺍니다. 프레임 제한(수직 동기화나 fps 제한)은 평소 쓰시는 대로 두셔도 됩니다.
다 끝나고 필요 없으면 작업 폴더(`\JarvisM0`)를 통째로 지우면 됩니다. Python, 모델, Strata(엔진과 설정 포함)는 모두 그 안에 설치하도록 지정해 두었습니다.

View File

@@ -41,7 +41,7 @@ PRESENTMON_SHA256 = "b2a706bc6ad475749e3b7e3409263aa1e6906d45bdcf993f6dbc0f66018
WINDOW_S = 60
SETTLE_S = 5 # Jarvis busy (or yielding) before a window starts
HITCH_MS = (50, 100) # a frame this long is a visible hitch
MIN_FRAMES = 300 # under this in a minute (5 fps) the game was not really drawing
MIN_FRAMES = 300 # under this in a minute (5 fps) with Jarvis off or idle, the game was not really drawing
ROUNDS = ("busy", "busy_yield", "busy_yield_2", "busy_2")
# The foreground window belongs to one of these when the user did not get back to the game.
NOT_A_GAME = {"windowsterminal.exe", "openconsole.exe", "conhost.exe", "cmd.exe", "powershell.exe",
@@ -183,12 +183,15 @@ class Yield:
def yield_problems(summary: dict) -> list[str]:
"""Why a yielding window did not yield: no process, nothing lowered, or a priority not put back."""
"""Why a yielding window did not yield: no process, a CPU or GPU priority left normal on any of
Jarvis's processes (yielding with some of them is not the yield being measured), or one not put back."""
out = []
if not summary.get("processes"):
n = summary.get("processes") or 0
if not n:
out.append("yield found no Jarvis process")
elif not summary.get("cpu_lowered") and not summary.get("gpu_lowered"):
out.append("yield lowered no priority")
for key, what in (("cpu_lowered", "CPU"), ("gpu_lowered", "GPU")):
if n and summary.get(key, 0) < n:
out.append(f"yield lowered the {what} priority of only {summary.get(key, 0)} of {n} processes")
if summary.get("not_restored"):
out.append(f"{summary['not_restored']} process(es) kept the lowered priority")
return out
@@ -252,26 +255,37 @@ def _num(value: str) -> float | None:
return None
def frame_stats(rows: list[dict], seconds: float) -> dict:
"""Frame rate, 1 % low (the 99th-percentile frame time as a rate) and hitches of the game's main
swap chain (the one with the most frames)."""
def frame_stats(rows: list[dict], seconds: float, min_frames: int = 0) -> dict:
"""What the screen showed of the game's main swap chain (the one with the most frames): the rate of
shown frames, the 1 % low (the 99th-percentile time between screen updates as a rate) and hitches,
all from the time each shown frame stayed before the next (msBetweenDisplayChange). A frame the
game presented but the screen never showed is counted in ``not_shown``; the rate the game
presented at is kept apart (``presented_fps``), since a game can present at 60 fps while the
screen changes far less often. ``min_frames`` (per minute) marks a window where the game was
hardly drawing; it is only given with Jarvis off or idle, so a game Jarvis slows down that much
still counts as the harm it is."""
chains: dict[str, list[dict]] = {}
for x in rows:
chains.setdefault(x.get("swapchainaddress", ""), []).append(x)
main = max(chains.values(), key=len) if chains else []
ms = [v for v in (_num(x.get("msbetweenpresents")) for x in main[1:]) if v is not None and v > 0]
out: dict[str, Any] = {"seconds": round(seconds, 1), "frames": len(ms)}
main = (max(chains.values(), key=len) if chains else [])[1:] # the first reaches back before the capture
presents = [v for v in (_num(x.get("msbetweenpresents")) for x in main) if v is not None and v > 0]
shown = [x for x in main if x.get("dropped") != "1"]
ms = [v for v in (_num(x.get("msbetweendisplaychange")) for x in shown) if v is not None and v > 0][1:]
out: dict[str, Any] = {"seconds": round(seconds, 1), "frames": len(ms), "presented": len(presents),
"not_shown": len(main) - len(shown)}
if presents:
out["presented_fps"] = round(len(presents) / (sum(presents) / 1000), 1)
if not ms:
return {**out, "valid": False, "invalid_because": ["the game drew no frames"]}
why = "the game drew no frames" if not presents else "PresentMon saw none of the frames reach the screen"
return {**out, "valid": False, "invalid_because": [why]}
srt = sorted(ms)
p99 = srt[min(len(srt) - 1, int(len(srt) * 0.99))]
out.update(fps=round(len(ms) / (sum(ms) / 1000), 1), low1_fps=round(1000 / p99, 1),
p99_ms=round(p99, 2), max_ms=round(srt[-1], 1),
hitches_over_ms={str(h): sum(v > h for v in ms) for h in HITCH_MS},
not_shown=sum(x.get("dropped") == "1" for x in main[1:]))
hitches_over_ms={str(h): sum(v > h for v in ms) for h in HITCH_MS})
reasons = []
if len(ms) < MIN_FRAMES * seconds / 60:
reasons.append(f"the game drew only {len(ms)} frames")
if len(ms) < min_frames * seconds / 60:
reasons.append(f"the screen showed only {len(ms)} of the game's frames")
out["valid"] = not reasons
if reasons:
out["invalid_because"] = reasons
@@ -361,6 +375,11 @@ def ask_for_a_game() -> bool:
return True
def _spoil(x: dict, why: str) -> None:
x["game"]["valid"] = False
x["game"]["invalid_because"] = x["game"].get("invalid_because", []) + [why]
def measure(r: StageResult, s: "llm.Strata", preset: dict, context: int, stt_python: str) -> None:
work = s.log.parent.parent
pm_log = s.log.with_name("presentmon.log")
@@ -393,14 +412,17 @@ def measure(r: StageResult, s: "llm.Strata", preset: dict, context: int, stt_pyt
x["vram_free_mib"] = used[1] - used[0]
with gpucap.UtilSampler() as util:
frames, err = capture(pm, game, WINDOW_S, work / "cache" / "frames.csv", pm_log)
g = frame_stats(frames, WINDOW_S)
g = frame_stats(frames, WINDOW_S, MIN_FRAMES if kind in ("off", "idle") else 0)
g["gpu_util"] = util.summary()
now = foreground_process()
if now is not None and now[0] != game:
g["valid"] = False
g["invalid_because"] = g.get("invalid_because", []) + ["the game was not in front at the end"]
if err:
# Frames from a capture that failed or was cut off do not cover the window.
r.error(f"frames {key}", err)
g["valid"] = False
g["invalid_because"] = g.get("invalid_because", []) + [f"the capture failed ({err})"]
x["game"] = g
rows.append(x)
if not g["valid"]:
@@ -450,20 +472,27 @@ def measure(r: StageResult, s: "llm.Strata", preset: dict, context: int, stt_pyt
x["llm"] = busy.summary()
for err in x["llm"]["errors"]:
r.error(f"frames {key} llm", err)
if not x["llm"]["decode_tok_s"].get("n"):
# Jarvis was not busy, so the window measured the game next to an idle Jarvis.
r.error(f"frames {key} llm", "no answer finished during the window")
_spoil(x, "the LLM finished no answer during the window")
if yielding:
x["yield"] = y.summary()
problems = yield_problems(x["yield"])
for why in problems:
r.error(f"frames {key} yield", why)
if problems:
x["game"]["valid"] = False
x["game"]["invalid_because"] = x["game"].get("invalid_because", []) + problems
for why in problems:
_spoil(x, why)
r.save()
busy_stt = stt.finish()
r["stt_busy"] = {k: busy_stt.get(k) for k in ("status", "single_s", "errors", "final_wait_s")
if k in busy_stt}
for err in llm.stt_gaps(busy_stt, llm._FINALS_ONLY):
r.error("frames stt", err)
# The STT's part of the load is not known to have run, in any busy window.
for x in rows:
if x["kind"].startswith("busy"):
_spoil(x, f"the STT load failed ({err})")
stt.close()
stt = None
s.stop()

View File

@@ -1659,29 +1659,48 @@ def test_a_player_that_never_comes_back_is_tried_again_per_window_and_the_stage_
# --- game_frames: the user's game's frame times next to Jarvis, plain and yielding by priority --
# PresentMon 2.6 --v1_metrics with display tracking (--no_track_input), as the kit runs it.
_PM_HEAD = ("Application,ProcessID,SwapChainAddress,Runtime,SyncInterval,PresentFlags,Dropped,TimeInSeconds,"
"msInPresentAPI,msBetweenPresents\n")
"msInPresentAPI,msBetweenPresents,AllowsTearing,PresentMode,msUntilRenderComplete,msUntilDisplayed,"
"msBetweenDisplayChange,msFlipDelay,msUntilRenderStart,msGPUActive\n")
def _pm_csv(frames_ms, chain="0x1", pid=7000, dropped=(), head=_PM_HEAD):
t, lines = 0.0, []
"""One row per presented frame; a shown frame's msBetweenDisplayChange is the time since the
screen last changed (PresentMon writes 0 for a frame that was never shown)."""
t, lines, since = 0.0, [], 0.0
for i, ms in enumerate(frames_ms):
t += ms / 1000
lines.append(f"game.exe,{pid},{chain},DXGI,0,0,{1 if i in dropped else 0},{t:.4f},0.1,{ms}")
since += ms
gone = i in dropped
lines.append(f"game.exe,{pid},{chain},DXGI,0,0,{1 if gone else 0},{t:.4f},0.1,{ms},0,"
f"Hardware: Independent Flip,1.0,2.0,{0 if gone else round(since, 4)},0,0.5,3.0")
if not gone:
since = 0.0
return head + "\n".join(lines) + "\n"
def test_frame_stats_read_the_main_swap_chain_with_rate_one_percent_low_and_hitches():
from m0lib import frames
main = [10.0] * 200 + [60.0, 120.0]
text = _pm_csv(main, dropped={5}) + _pm_csv([500.0] * 5, chain="0x2", head="")
text = _pm_csv(main) + _pm_csv([500.0] * 5, chain="0x2", head="")
g = frames.frame_stats(frames.parse_csv(text), 3.0)
counted = main[1:] # the first row's interval reaches back before the capture
assert g["valid"] and g["frames"] == len(counted)
counted = main[2:] # the first rows' intervals reach back before the capture
assert g["valid"] and g["frames"] == len(counted) and g["not_shown"] == 0
assert g["fps"] == round(len(counted) / (sum(counted) / 1000), 1)
p99 = sorted(counted)[int(len(counted) * 0.99)]
assert g["low1_fps"] == round(1000 / p99, 1) and g["max_ms"] == 120.0
assert g["hitches_over_ms"] == {"50": 2, "100": 1} and g["not_shown"] == 1
assert g["hitches_over_ms"] == {"50": 2, "100": 1}
def test_frames_the_screen_never_showed_count_as_a_stutter_even_when_the_game_presents_smoothly():
from m0lib import frames
# The game presents every 16.7 ms, but only every tenth frame reaches the screen.
rows = frames.parse_csv(_pm_csv([16.67] * 3600, dropped={i for i in range(3600) if i % 10}))
g = frames.frame_stats(rows, 60)
assert g["presented_fps"] == round(1000 / 16.67, 1) and g["not_shown"] > 3000
assert g["fps"] < 7 and g["low1_fps"] < 7 and g["hitches_over_ms"]["100"] == g["frames"]
assert g["valid"] # a stutter is the harm being measured, not a spoilt window
def test_frame_stats_read_presentmon_2_column_names_too():
@@ -1693,8 +1712,11 @@ def test_frame_stats_read_presentmon_2_column_names_too():
def test_a_window_where_the_game_drew_nothing_or_almost_nothing_is_not_counted():
from m0lib import frames
assert not frames.frame_stats([], 60)["valid"]
few = frames.frame_stats(frames.parse_csv(_pm_csv([1000.0] * 30)), 60)
assert not few["valid"] and "frames" in few["invalid_because"][0]
few = frames.parse_csv(_pm_csv([1000.0] * 30))
# With Jarvis off or idle that means the game was not drawing; next to a busy Jarvis it is a stutter.
off = frames.frame_stats(few, 60, frames.MIN_FRAMES)
assert not off["valid"] and "frames" in off["invalid_because"][0]
assert frames.frame_stats(few, 60)["valid"]
def test_compare_pools_the_valid_windows_against_the_game_alone():
@@ -1741,7 +1763,9 @@ def test_yield_lowers_cpu_and_gpu_priority_and_puts_back_what_each_process_had(m
assert pr.now[1] == (0x20, 2) and pr.now[2] == (0x8000, 2)
s = y.summary()
assert s == {"processes": 3, "cpu_lowered": 2, "gpu_lowered": 2, "restored": 2, "not_restored": 1}
assert frames.yield_problems(s) == ["1 process(es) kept the lowered priority"]
assert frames.yield_problems(s) == ["yield lowered the CPU priority of only 2 of 3 processes",
"yield lowered the GPU priority of only 2 of 3 processes",
"1 process(es) kept the lowered priority"]
assert frames.yield_problems(frames.Yield([]).summary()) == ["yield found no Jarvis process"]
@@ -1770,7 +1794,8 @@ def test_presentmon_records_only_the_game_for_a_fixed_time_and_a_bad_download_is
GAME_PID = 7000
def _run_frames_stage(tmp_path, monkeypatch, fake_server, admin=True, front=(GAME_PID, "game.exe"), pr=None):
def _run_frames_stage(tmp_path, monkeypatch, fake_server, admin=True, front=(GAME_PID, "game.exe"), pr=None,
capture_err=None, stt=None):
from m0lib import frames
pr = _FakePriorities() if pr is None else pr
captured = []
@@ -1784,10 +1809,10 @@ def _run_frames_stage(tmp_path, monkeypatch, fake_server, admin=True, front=(GAM
def capture(exe, pid, seconds, out_csv, log):
captured.append((pid, dict(pr.now)))
return frames.parse_csv(_pm_csv([16.0] * 4000, pid=pid)), None
return frames.parse_csv(_pm_csv([16.0] * 4000, pid=pid)), capture_err
monkeypatch.setattr(frames, "capture", capture)
stt = _FakeStt()
stt = _FakeStt() if stt is None else stt
r, started, running = _run_levels_stage(tmp_path, monkeypatch, fake_server, _vram, only="frames",
extra_opts=["stt_python=py"], stt=stt)
return r, started, running, stt, pr, captured
@@ -1830,10 +1855,33 @@ def test_frames_stage_needs_administrator_rights_and_the_game_in_front_before_st
def test_a_yield_that_lowered_nothing_does_not_count_as_a_yielding_window(tmp_path, monkeypatch, fake_server):
pr = _FakePriorities(ignored={20, 21, STT_LAUNCHER_PID, STT_LAUNCHER_PID + 1})
# One of Jarvis's four processes keeps its priorities: that is not the yield being measured.
pr = _FakePriorities(ignored={21})
r, *_ = _run_frames_stage(tmp_path, monkeypatch, fake_server, pr=pr)
assert r["comparison"]["busy_yield"]["windows"] == 0 and r["comparison"]["busy"]["windows"] == 2
assert r["status"] == "partial" and any("lowered no priority" in e["error"] for e in r["errors"])
assert r["status"] == "partial" and any("only 3 of 4" in e["error"] for e in r["errors"])
def test_a_failed_capture_is_not_counted(tmp_path, monkeypatch, fake_server):
r, *_ = _run_frames_stage(tmp_path, monkeypatch, fake_server, capture_err="PresentMon exited with timeout")
assert not any(x["game"]["valid"] for x in r["frame_rows"])
assert all(r["comparison"][k]["windows"] == 0 for k in ("off", "busy", "busy_yield"))
def test_a_busy_window_where_jarvis_answered_nothing_is_not_counted(tmp_path, monkeypatch, fake_server):
from m0lib import frames
monkeypatch.setattr(frames.BusyLlm, "_loop", lambda self: None) # no answer ever finishes
r, *_ = _run_frames_stage(tmp_path, monkeypatch, fake_server)
assert r["comparison"]["off"]["windows"] == 2
assert r["comparison"]["busy"]["windows"] == 0 and r["comparison"]["busy_yield"]["windows"] == 0
assert r["status"] == "partial"
def test_busy_windows_do_not_count_when_the_stt_load_failed(tmp_path, monkeypatch, fake_server):
stt = _FakeStt(finish_result={"status": "timeout", "errors": ["stt worker did not stop within 300 s"]})
r, *_ = _run_frames_stage(tmp_path, monkeypatch, fake_server, stt=stt)
assert r["comparison"]["off"]["windows"] == 2
assert r["comparison"]["busy"]["windows"] == 0 and r["comparison"]["busy_yield"]["windows"] == 0
def test_frames_stage_is_on_demand_with_the_stt_python_and_an_elevating_one_click_runner():