Skip to content

Commit

Permalink
chore: Added code duration recording to CodeChunk/Python
Browse files Browse the repository at this point in the history
  • Loading branch information
beneboy committed Sep 2, 2019
1 parent 7f2bf64 commit 3e2da3b
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion py/stencila/schema/interpreter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import argparse
import ast
import base64
import datetime
import json
import logging
import sys
Expand Down Expand Up @@ -70,6 +71,26 @@ class CodeChunkExecution(typing.NamedTuple):
ExecutableCode = typing.Union[CodeChunkExecution, CodeExpression]


class CodeTimer:
_start_time: datetime.datetime
duration: typing.Optional[datetime.timedelta] = None

def __enter__(self):
self.duration = None
self._start_time = datetime.datetime.now()
return self

def __exit__(self, exc_type, exc_val, exc_tb):
self.duration = datetime.datetime.now() - self._start_time

@property
def duration_ms(self) -> float:
if not self.duration:
raise RuntimeError('CodeTimer has not yet been run')

return self.duration.total_seconds() * 1000


class StdoutBuffer(TextIOWrapper):
def write(self, string: typing.Union[bytes, str]) -> int:
if isinstance(string, str):
Expand Down Expand Up @@ -235,6 +256,7 @@ def parse_code_chunk(chunk: CodeChunk) -> CodeChunkParseResult:
else:
assigns.add(v)
seen_vars.add(target_name)
seen_vars.add(target_name)
elif isinstance(statement, ast.Expr) and isinstance(statement.value, ast.Call):
if hasattr(statement.value, 'args'):
for arg in statement.value.args:
Expand Down Expand Up @@ -355,7 +377,9 @@ def execute_code_chunk(self, chunk_execution: CodeChunkExecution, _locals: typin

with redirect_stdout(s):
try:
result = run_function(code_to_run, self.globals, _locals)
with CodeTimer() as ct:
result = run_function(code_to_run, self.globals, _locals)
chunk.duration = ct.duration_ms
except Exception as e:
set_code_error(chunk, e)

Expand Down

0 comments on commit 3e2da3b

Please sign in to comment.