#!/usr/local/cpython-3.6/bin/python3

"""Performance comparison between cpython 3.6 and pypy3 5.8.0 with a backshift focus."""

import os
import lzma
import time

def utime_test():
    """
    Test the speed of os.utime().
    This is faster on pypy3 5.8.0.
    """
    # Create the file
    with open('testfile', 'w'):
        pass
    # uptime its timestamp one million times
    time0 = time.time()
    for _unused in range(1000000):
        os.utime('testfile')
    time1 = time.time()
    print(time1 - time0)

def lzma_compression_test():
    """
    Test the speed of lzma compression.
    This is faster on pypy3 5.8.0 with lzma fixes.
    """
    # Create an uncompressed string
    string = b'a' * 1000000
    # compress it ten times
    time0 = time.time()
    for counter in range(10):
        _unused = counter
        result = lzma.compress(string)
        _unused = result
    time1 = time.time()
    print(time1 - time0)

def lzma_decompression_test():
    """
    Test the speed of lzma decompression.
    This is about 31.5% slower on pypy3 5.8.0 with lzma fixes than on CPython 3.6's native lzma module.
    """
    # Create a compressed string
    string = b'a' * 1000000
    compressed_data = lzma.compress(string)
    # decompress it one hundred times
    time0 = time.time()
    for counter in range(100):
        _unused = counter
        result = lzma.decompress(compressed_data)
        _unused = result
    time1 = time.time()
    print(time1 - time0)

def alt_lzma_decompression_test():
    # pylint: disable=protected-access
    # protected-access: We want to access a protected member, unfortunately - for performance reasons.
    """
    Test the speed of lzma decompression via an alternative means.
    This is around 32.1% slower on pypy3 5.8.0 with lzma fixes than on CPython 3.6's native lzma module.
    """
    # Create a compressed string
    string = b'a' * 10**7
    compressed_data = lzma.compress(string, format=lzma.FORMAT_XZ)
    # Maximum decompressed size is 256 meg
    max_size = 2**28
    time0 = time.time()
    # decompress it one hundred times
    first_time = True
    for counter in range(100):
        _unused = counter
        decompressor = lzma.LZMADecompressor(format=lzma.FORMAT_XZ, memlimit=max_size)
        if hasattr(decompressor, '_bufsiz'):
            if first_time:
                print('Setting _bufsize to {}'.format(max_size))
                first_time = False
            decompressor._bufsiz = max_size
        result = decompressor.decompress(compressed_data)
        _unused = result
    time1 = time.time()
    print(time1 - time0)

def main():
    """Main function."""
    # utime_test()
    # lzma_compression_test()
    # lzma_decompression_test()
    alt_lzma_decompression_test()

main()