Skip to content

Instantly share code, notes, and snippets.

@hecomi
Last active June 11, 2018 00:01
Show Gist options
  • Save hecomi/4bd15b07fb30ffea8eaf807ce766f6ec to your computer and use it in GitHub Desktop.
Save hecomi/4bd15b07fb30ffea8eaf807ce766f6ec to your computer and use it in GitHub Desktop.
libjpeg-turbo の速度を雑にテストしたやつ
#include <cstdio>
#include <iostream>
#include <fstream>
#include <chrono>
#include <memory>
#include <turbojpeg.h>
// https://tenshil.blogspot.com/2017/06/visualstudio-2015-error-lnk2019.html
FILE _iob[] = { *stdin, *stdout, *stderr };
extern "C" FILE * __cdecl __iob_func(void)
{
return _iob;
}
namespace
{
constexpr int kJpegQuality = 75;
constexpr int kWidth = 256;
constexpr int kHeight = 256;
}
class Timer
{
public:
Timer()
: m_start(std::chrono::high_resolution_clock::now())
{
}
~Timer()
{
const auto end = std::chrono::high_resolution_clock::now();
const auto time = std::chrono::duration_cast<std::chrono::microseconds>(end - m_start);
std::cout << time.count() << std::endl;
}
private:
std::chrono::steady_clock::time_point m_start;
};
std::unique_ptr<unsigned char[]> createBuffer()
{
auto buffer = std::make_unique<unsigned char[]>(kWidth * kHeight * 3);
for (int x = 0; x < kWidth; ++x)
{
for (int y = 0; y < kHeight; ++y)
{
for (int c = 0; c < 3; ++c)
{
const auto i = c + (3 * x) + (3 * kWidth) * y;
unsigned char value = static_cast<unsigned char>(128.f * x / kWidth + 128.f * y / kHeight);
value = (value + c * 85) % 255;
buffer[i] = value;
}
}
}
return buffer;
}
void compress(unsigned char *buffer, const char *name)
{
unsigned char *image = nullptr;
unsigned long size = 0;
auto handle = tjInitCompress();
{
Timer timer;
tjCompress2(
handle,
buffer,
kWidth,
0,
kHeight,
TJPF_RGB,
&image,
&size,
TJSAMP_444,
kJpegQuality,
TJFLAG_FASTDCT);
}
std::ofstream ofs(name, std::ios::binary);
ofs.write(reinterpret_cast<char *>(image), size);
ofs.close();
tjDestroy(handle);
tjFree(image);
}
void decompress(const char *in, const char *out)
{
std::ifstream ifs(in, std::ios::binary);
ifs.seekg(0, std::ios::end);
const auto eof = ifs.tellg();
ifs.clear();
ifs.seekg(std::ios::beg);
ifs.tellg();
const auto eoh = ifs.tellg();
const auto size = static_cast<unsigned long>(eof - eoh);
auto image = std::make_unique<unsigned char[]>(size);
ifs.read(reinterpret_cast<char*>(image.get()), size);
ifs.close();
auto buffer = std::make_unique<unsigned char[]>(kWidth * kHeight * 3);
{
Timer timer;
int jpegSubsamp, width, height;
auto handle = tjInitDecompress();
tjDecompressHeader2(handle, image.get(), size, &width, &height, &jpegSubsamp);
tjDecompress2(handle, image.get(), size, buffer.get(), width, 0, height, TJPF_RGB, TJFLAG_FASTDCT);
}
compress(buffer.get(), out);
}
int main()
{
compress(createBuffer().get(), "out.jpg");
decompress("out.jpg", "out2.jpg");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment