のぴぴのメモ

自分用のLinuxとかの技術メモ

Python3でナノ秒の計測をする方法

Pytho処理時間をナノ秒で計測する方法です。
python3.7で追加された、time.clock_gettime_ns()を利用することで実現しています。*1

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import time

def main():
    start = time.clock_gettime_ns(time.CLOCK_MONOTONIC)
    <処理内容を記載>
    end = time.clock_gettime_ns(time.CLOCK_MONOTONIC)

    print('time: {}'.format(end - start))

if __name__ == "__main__":
    sys.exit(main())
  • 結果の単位は、ナノ秒(10^-9)"です。
  • time.CLOCK_MONOTONIC"は、単調増加の時間で 表現されるクロックを取得するオプションです。*2

補足

"end - start"のオーバーフローが気になる

time.clock_gettime_ns()は、int型を返します(なので上記コードのstart, endはint型)。

int型の場合overflowが気になりますが、python3のint型は仕様上上限なしでメモリサイズに空きがある限り拡大できるようです(python2のlong型がint型になった)
なので、python3の場合はオーバーフロー気にしなくて良さそうですね

Integers
PEP 0237: Essentially, long renamed to int. That is, there is only one built-in integral type, named int; but it behaves mostly like the old long type.
PEP 0238: An expression like 1/2 returns a float. Use 1//2 to get the truncating behavior. (The latter syntax has existed for years, at least since Python 2.2.)
The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
The repr() of a long integer doesn’t include the trailing L anymore, so code that unconditionally strips that character will chop off the last digit instead. (Use str() instead.)
Octal literals are no longer of the form 0720; use 0o720 instead.

https://docs.python.org/3.1/whatsnew/3.0.html#integers