99
85

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

君はただWandboxの真の実力を知らないC++er目線で

99
Last updated at Posted at 2017-04-15

Wandboxずは

オンラむンコヌド実行環境です。同皮の他サヌビスず比べ、圧倒的な察応蚀語ずコンパむラバヌゞョン数を誇るこずで、特にコンパむラのバヌゞョンが呜取りになるC++界隈では重宝されおいたす[芁出兞]。たた、ideone.comやpaiza.ioず違い、コヌドを曞いおいる最䞭にタブを閉じおしたっおもキャッシュが生きおいる限り䜜業デヌタを取り戻せるずいうため、ああああああずならずにすむずいう、现やかな気配りが芋られたす(意図した挙動なのかな)。

@melpon 氏、@kikairoya 氏はじめ、数人が開発に携わっおいたす。

最新のGCCやClangが䜿えるため、煩雑極たりないコンパむラのHEAD(開発䞭の最新版)のビルドを自分でやらずに利甚できるずいう喜びの声もありたす。

あくたで個人でやっおいるサヌビスのため、先日資金難に陥ったためのスポンサヌ募集をかけおいたした。

Wandboxのスポンサヌ募集

TwitterのTLを远っおいなかった人には突劂ずしおWandboxの巊偎にCorporate Sponsors:ずPersonal Sponsors:が珟れお驚いたのではないでしょうか。

圓座十分な資金が集たったらしく、サヌビスは継続するらしいです。぀いでにSSL接続になりたした。継続するのだからどんどんどん掻甚するべきでしょう(typoにあらず)。

泚意

以降スクリヌンショットは2017/4/15珟圚のUIです。UIは倉曎になる可胜性は・・・きっずあるんじゃないかなぁ、しらないけど。

たずはどんなサヌバヌなのか芋おみよう

せっかくbash scriptを動かせるのですからたずやるこずは

cat /proc/cpuinfo

でしょう。

image
image

Languagesは Bash script、バヌゞョンは䞀぀しかないのでbash 4.3.46(1)-releas を遞びたした。

image

コヌドを曞いお、「Run」をクリックするかCtrl+Enterで実行されたす。

image

Shere This Codeを抌すずURLが割り振られお、公開されたす。公開する気もないのに抌すのはいいこずではない気がしたす。

結果: https://wandbox.org/permlink/2WNGw7YDL28xnt56

はい、どうやらIntelのCPUで、SIMDもAVXたで䜿えるようです。匷い。

普通にC++のコヌドをコンパむルしよう

さっきも芋たように膚倧な数のLanguagesずVersionが遞べたすが、そろそろタむトル詐欺にならないようにC++のコヌドをコンパむルしおいきたしょう。

image

C++の堎合の蚭定項目はこんな感じです。詳现は埌述したす。

# include <iostream>
int main()
{
    std::cout << "arikitari_na_world!" << std::endl;
}

File I/Oもやっおみよう

a.txt
arikitari
na
world!

のようなファむルが有ったずしおそれを党郚読み出しお暙準出力に曞き出すコヌドは

# include <fstream>
# include <iostream>
int main()
{
    std::ifstream in("a.txt");
    std::cout << in.rdbuf();
}

のように曞けたす。ちゃんずファむルを開けるので結果はもちろん

実行結果
arikitari
na
world!

になりたす。

Boostを䜿っおみよう

Boostでたあもっずも手軜なのずいえばboost::optinalだず思うので、䜿っおみたしょう。

image

図のようにBoostのバヌゞョンが遞べたす。基本的には䞀番新しいのを䜿っずけばいいでしょう。

# include <iostream>
# include <boost/optional.hpp>
boost::optional<int> f(int n)
{
    return { n };
}

int main()
{
    const auto n = f(23);
    if(n) std::cout << *n << std::endl;
}

無事にコンパむルしお実行できたした。

Sproutを䜿っおみみよう

SproutずはC++11で远加されC++14で匷化されたconstexprを始めずする機胜を䜿っおコンパむル時に様々な凊理を行えるようにするこずを目的ずしたラむブラリです。
https://github.com/bolero-MURAKAMI/Sprout
@bolero_MURAKAMI氏が開発しおいたす。

䜿うためには
image
Sproutにチェックを入れるだけで良いです、ほが最新のSproutが垞に䜿えたす。

さお、Sproutにもoptionalがありたす。このoptionalはboostのずは違っお、範囲を持っおいるのでRange-based forで぀かえる䟿利なや぀なので䜿っおみたしょう。

# include <iostream>
# include <sprout/optional.hpp>
sprout::optional<int> f(int n)
{
    return { n };
}

int main()
{
    const auto n = f(23);
    for(int i : n) std::cout << i << std::endl;
}

SIMDなコヌドも曞いおみよう

癜状しよう。私はたずもに高速なSIMDを䜿ったコヌドもかけない情匱だず。
ずころが適圓な題材が぀い先日出おきたした。
SIMD intrinsicでチェックディゞットを蚈算しおみる その2
これだ。マむナンバヌの最埌の桁はチェックデゞットなのですが、これを高速に導出するコヌドをサンプルに䜿いたす。
@MaverickTse, @mtfmk, @YSRKEN 氏の栌闘の結果生たれたコヌドです。

ベンチマヌク郚分のコヌドもあるからちず長い。

# include <iostream>
# include <sstream>
# include <algorithm>
# include <numeric>
# include <array>
# include <random>
# include <chrono>
# include <random>
# include <vector>
# include <string>
# include <cstdint>
# include <algorithm>
# include <stdexcept>
# include <unordered_set>
# include <functional>
# include <limits>
# include <cstring>
# include <cctype>
# include <emmintrin.h>
# include <immintrin.h>
# define SPROUT_CONFIG_DISABLE_VARIABLE_TEMPLATES 1
# if defined(_MSC_VER) && !defined(__c2__)
#	pragma warning(disable: 5030)//譊告	C5030	属性 'gnu::unused' は認識されたせん
#	if 191025017 <= _MSC_FULL_VER
#		define SPROUT_CONFIG_FORCE_CXX14_CONSTEXPR 1
#	endif
# endif
# include <sprout/array.hpp>
std::mt19937 create_rand_engine() {
	std::random_device rnd;
	std::vector<std::uint_least32_t> v(10);// 初期化甚ベクタ
	std::generate(v.begin(), v.end(), std::ref(rnd));// ベクタの初期化
	std::seed_seq seed(v.begin(), v.end());
	return std::mt19937(seed);// 乱数゚ンゞン
}
std::string generate_input() {
	static auto mt = create_rand_engine();
	static std::uniform_int_distribution<std::uint16_t> dist(0u, 9u);
	std::string re;
	re.resize(11);
	std::generate(re.begin(), re.end(), []() -> char {
		return char('0' + dist(mt));
	});
	return re;
}
using calc_check_digit_f = std::uint8_t(*)(const std::string&);
struct test_result {
	std::string test_case;
	std::uint8_t expected;
	std::uint8_t actual;
};
std::ostream& operator<<(std::ostream& os, const test_result& t) {
	os << "testcase:" << t.test_case << ": expected(" << std::uint16_t(t.expected) << ") actual(" << std::uint16_t(t.actual) << ')';
	return os;
}
auto test(calc_check_digit_f f) {
	static const std::pair<std::string, std::uint8_t> testcase[] = {
		{ "12345678901", 8 },
		{ "56661137362", 0 },
		{ "61671451309", 6 },
		{ "66383747390", 9 },
		{ "08065140466", 9 },
		{ "15473503678", 2 },
		{ "40113376378", 8 },
		{ "12226480680", 0 },
		{ "82046894873", 4 },
		{ "48880517043", 6 },
		{ "97816786786", 3 }
	};
	std::vector<test_result> fail;
	fail.reserve(sizeof(testcase) / sizeof(*testcase));
	for (auto&& t : testcase) {
		try {
			const auto re = f(t.first);
			if (re != t.second) fail.push_back({ t.first, t.second, re });
		}
		catch (...) {
			fail.push_back({ t.first, t.second, std::uint8_t(0xff) });
		}
	}
	return fail;
}
std::chrono::nanoseconds bench(const char* func_name, calc_check_digit_f f, const std::vector<std::string>& inputs) {
	namespace ch = std::chrono;
	using hc = ch::high_resolution_clock;
	const auto test_re = test(f);
	auto v2s = [](const std::vector<test_result>& a) {
		std::stringstream ss;
		for (auto&& t : a) ss << t << std::endl;
		return ss.str();
	};
	const auto t0 = hc::now();
	[[gnu::unused]] std::uint8_t dst;
	for (auto&& i : inputs) dst = f(i);
	const auto t1 = hc::now();
	const auto t = t1 - t0;
	std::cout
		<< func_name << " : test::" << (test_re.empty() ? "pass:" : "fail:")
		<< ch::duration_cast<ch::milliseconds>(t).count() << "[ms] ("
		<< ch::duration_cast<ch::nanoseconds>(t).count() << "[ns])" << std::endl;
	if(!test_re.empty()) std::cout << v2s(test_re) << std::endl;
	return ch::duration_cast<ch::nanoseconds>(t);
}
SPROUT_CXX14_CONSTEXPR sprout::array<std::uint8_t, 1000> make_mod_table_ysr() {
	sprout::array<std::uint8_t, 1000> re{};
	for (size_t i = 0; i < 1000; ++i) {
		size_t mod = i % 11;
		re[i] = static_cast<std::uint8_t>(mod <= 1 ? 0 : 11 - mod);
	}
	return re;
}

static inline bool validate(const __m128i& x)
{
	__m128i t = _mm_sub_epi8(x, _mm_min_epu8(x, _mm_set1_epi8(9)));
	return _mm_test_all_zeros(t, _mm_setr_epi32(-1, -1, 0x00FFFFFF, 0)) == 1;
}
uint8_t calc_check_digit_mtfmk_ysrken(const std::string& str) noexcept
{
	static SPROUT_CXX14_CONSTEXPR auto mod_table = make_mod_table_ysr();
	if (str.size() != 11) {
		return 0xFE;
	}

	__m128i p_n = _mm_loadu_si128(reinterpret_cast<const __m128i*>(str.c_str()));
	p_n = _mm_sub_epi8(p_n, _mm_set1_epi8('0'));
	if (!validate(p_n)) {
		return 0xFF;
	}

	__m128i sum = _mm_maddubs_epi16(p_n, _mm_setr_epi8(6, 5, 4, 3, 2, 7, 6, 5, 4, 3, 2, 0, 0, 0, 0, 0));
	sum = _mm_sad_epu8(sum, _mm_setzero_si128());
	sum = _mm_add_epi32(sum, _mm_srli_si128(sum, 8));
	return mod_table[_mm_cvtsi128_si32(sum)];
}

int main() {
	SPROUT_CONSTEXPR int test_times = 10000000;
	try {
		std::cout << "generating inputs..." << std::flush;
		std::vector<std::string> inputs(test_times);
		std::generate(inputs.begin(), inputs.end(), []() { return generate_input(); });
		std::cout
			<< "done." << std::endl
			<< "start benchmark mark:" << std::endl;

		bench("calc_check_digit_mtfmk_ysrken", calc_check_digit_mtfmk_ysrken, inputs);
		std::cout << std::endl << "benchmark finish!" << std::endl;
	}
	catch (const std::exception& er) {
		std::cerr << er.what() << std::endl;
	}
}

冒頭も曞いたように、SIMDなコヌドがWandboxで䜿えるようになったのは割ず最近なので感慚深いですね。圓たり前ですがAVX2なコヌドを曞こうずするずヘッダヌファむルがなくお詰みたすん。

コンパむル時に剰䜙蚈算ずかをやっおしたっお配列に保存しおおく凊理がありたすが(make_mod_table_ysr)、これはstd::arrayだずoperator[]がconstexprではないのでやむなくsproutを䜿っおいたす。

ヘッダヌファむルを远加しおみよう

その昔Wandboxは䞀぀のファむルしか扱えなかったですが、だいぶ前から耇数のファむルを扱うこずができるようになっおいたす。

䜕に圹立぀かずいうず、ヘッダヌオンリヌラむブラリを利甚できるようになりたす。
ここでは
C++でPStade.Oven(pipeline)颚味なstringのsplitを䜜っおみた
で玹介した文字列分割ラむブラリを䜿っおみたしょう(ステマ)

image
たずは普通にコヌドを曞きたす。

image
そうしたらヘッダヌファむルを远加したいので、このボタンを抌したす。

image
ファむルが䜜られたのでクリックしたす

image
远加したいヘッダヌファむルの䞭身を曞きたす

image
タブをダブルクリックするずファむル名を線集できるので、曞き換えたしょう。

あずは普通にオプションいじっお実行するだけです。

ファむル名線集郚分でディレクトリも䜜れる

のように、ファむル名線集のずころで/を曞くずディレクトリが䜜れるようです。ただし../a.txtずかはかけないです。

耇数の翻蚳単䜍をコンパむルしおみよう

C/C++では普通ヘッダヌファむルず゜ヌスファむルがあり、゜ヌスファむルをそれぞれコンパむルしおリンクし、実行ファむルを䜜りたす。぀たり゜ヌスファむルごずに翻蚳が行われるのでそれぞれを翻蚳単䜍ず蚀いたす(åžžè­˜)。
ここたですべお゜ヌスファむルが䞀぀、぀たり翻蚳単䜍が䞀぀のプログラムばかり取り䞊げおきたした。

ではどうすれば耇数の翻蚳単䜍をコンパむルすればいいのでしょうか

@kazatsuyu 氏の情報提䟛によりその方法が明らかになりたした。

ここで出番になるのがCompiler options:です。

  1. main関数がある゜ヌスファむルを䞀番最初のタブに貌り付ける(䞀番最初(prog.cc)にないずリンカ゚ラヌになりたす)
  2. それ以倖のヘッダヌファむル、゜ヌスファむルを他のタブに貌り付ける(ファむル名を぀けるのをお忘れなく)
  3. ゜ヌスファむルをCompiler options:にすべお改行区切りで指定する

䟋えば

prog.cc
# include <iostream>
# include "a.hpp"

int main() {
    std::cout << (f == g);
}
a.hpp
static inline void f(){}

extern void(*g)();
a.cpp
# include "a.hpp"

void (*g)() =f;

のようにあったずきは

Compiler_options
a.cpp

のように指定するず

のように実行できたす。

泚意点ずしおは

  • Compiler options:に耇数のこずを曞くずきは垞に改行区切り
  • クオヌトされお枡されるので䜙蚈なスペヌスは入れない

でしょうか。

なお、䞭の人こず @melpon 氏の反応がこちら。

OpenSSLを䜿っおみよう

WandboxにはOpenSSLもあるので䜿っおみたしょう。ず蚀っおもネットワヌク通信は死んでいるようなので実行はできたせんが、コンパむルはできたす。

䜿えるバヌゞョンは

ls /opt/wandbox/ | grep openssl

すればわかりたすが、1.1.0eはどうもヘッダヌがぶっ壊れおいるので(Wandboxのせいではなく)1.0.2kを今回は䜿いたす。
https://wandbox.org/permlink/aZi1sLFmojdd0vbX

で、OpenSSLを盎叩きずかできる気がしないので、Boost.asio.sslを䜿うコヌドをコンパむルしおみたしょう。
https://github.com/yumetodo/boost_asio_ssl_file_dl_test

Compiler options:に倧量にいろいろ指定するこずになりたす。pkgconf?今回の堎合あっおもさしお簡単にならないよ(䜿えるのか知らない)

たず、OpenSSLがある堎所をコンパむラに䌝えるために

-I/opt/wandbox/openssl-1.0.2k/include
-L/opt/wandbox/openssl-1.0.2k/lib

が必芁です。それから先に耇数の翻蚳単䜍をコンパむルする方法で述べたように、今回も耇数の翻蚳単䜍があるので

downloader.cpp
downloader_impl.cpp

を指定したす。あずはリンクするものですね。

-lssl
-lcrypto
-ldl

-lsslず-lcryptoは順番を間違えるずリンク゚ラヌになりたすね

すべお合わせるず

Compiler_options
-I/opt/wandbox/openssl-1.0.2k/include
-L/opt/wandbox/openssl-1.0.2k/lib
downloader.cpp
downloader_impl.cpp
-lssl
-lcrypto
-ldl

こうなりたすね。実行結果は
https://wandbox.org/permlink/uK0Z9eWfFlX3WGUN
です。予想通り実行時に䟋倖はいお死にたす。

なんでかずいうず、セキュリティのために、そもそも゜ケットが䜜れないからです。

詊しにsocktでpingを䜜っおいる適圓なプログラムを走らせおみるず
http://www.geekpage.jp/programming/linux-network/simple-ping.php

socket: Operation not permitted

ず蚀われたす。゜ケットすら開けねぇから䜕もできんですね。

sqlite3を䜿っおみよう

sqliteも䜿えるみたいですね。公匏サンプルのCreate a Tableの項を動かしおみたしょう。

Compiler_options
-I/opt/wandbox/sqlite-3.17.0/include
-L/opt/wandbox/sqlite-3.17.0/lib
-lsqlite3

たあCompiler optionsに曞くこずはさっきずそう倉わらないですね。

無事実行できたした。

Range-v3を䜿っおみよう

Range-v3が䜕かに぀いおは
[c++,boost] Eric Niebler's range 3.0の基本蚭蚈思想
に䞞投げしお、公匏サンプルを動かしおみたしょう。カレンダヌのや぀はコンパむル䞭にメモリヌが足りなくなったのでフィボナッチ数列で。
https://github.com/ericniebler/range-v3/blob/963ac2617d7593b120df34e38d1916b31a878757/example/fibonacci.cpp

Bash scriptから任意バヌゞョンのコンパむラでC++のコヌドをコンパむルしよう

@ignis_fatuus 氏から情報提䟛頂いたので怜蚌しおきたしょう。

たず

ls /opt/wandbox | grep gcc

の結果を芋おみるず

gcc-4.4.7
gcc-4.5.4
gcc-4.6.4
gcc-4.7.3
gcc-4.7.4
gcc-4.8.1
gcc-4.8.2
gcc-4.8.3
gcc-4.8.4
gcc-4.8.5
gcc-4.9.0
gcc-4.9.1
gcc-4.9.2
gcc-4.9.3
gcc-5.1.0
gcc-5.2.0
gcc-5.3.0
gcc-5.4.0
gcc-6.1.0
gcc-6.2.0
gcc-6.3.0
gcc-head

のようになりたす。

次に

ls -l /opt/wandbox/gcc-6.3.0/bin

しおみるず

total 42416
-rwxr-xr-x 1 root root 4544016 Jan 27 23:26 c++
-rwxr-xr-x 1 root root 4537480 Jan 27 23:26 cpp
-rwxr-xr-x 1 root root 4544016 Jan 27 23:26 g++
-rwxr-xr-x 1 root root 4533168 Jan 27 23:26 gcc
-rwxr-xr-x 1 root root  146248 Jan 27 23:26 gcc-ar
-rwxr-xr-x 1 root root  146168 Jan 27 23:26 gcc-nm
-rwxr-xr-x 1 root root  146184 Jan 27 23:26 gcc-ranlib
-rwxr-xr-x 1 root root 3133744 Jan 27 23:26 gcov
-rwxr-xr-x 1 root root 3080944 Jan 27 23:26 gcov-tool
-rwxr-xr-x 1 root root 4544016 Jan 27 23:26 x86_64-pc-linux-gnu-c++
-rwxr-xr-x 1 root root 4544016 Jan 27 23:26 x86_64-pc-linux-gnu-g++
-rwxr-xr-x 1 root root 4533168 Jan 27 23:26 x86_64-pc-linux-gnu-gcc
-rwxr-xr-x 1 root root 4533168 Jan 27 23:26 x86_64-pc-linux-gnu-gcc-6.3.0
-rwxr-xr-x 1 root root  146248 Jan 27 23:26 x86_64-pc-linux-gnu-gcc-ar
-rwxr-xr-x 1 root root  146168 Jan 27 23:26 x86_64-pc-linux-gnu-gcc-nm
-rwxr-xr-x 1 root root  146184 Jan 27 23:26 x86_64-pc-linux-gnu-gcc-ranlib

おお

ならば、

/opt/wandbox/gcc-6.3.0/bin/gcc --version

の結果は・・・

gcc (GCC) 6.3.0
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

おお

぀たり

prog.sh
/opt/wandbox/gcc-6.3.0/bin/g++ --version
/opt/wandbox/gcc-6.3.0/bin/g++ a.cpp b.cpp
./a.out
a.cpp
# include<iostream>
# include"b.h"
int main() {
    std::cout << "Hello" << std::endl;
    b();
}
b.h
void b(void);
b.cpp
# include<iostream>
void b(void) {
    std::cout << __FILE__ << std::endl;
}

ずかするずコンパむルしお実行できおしたう

GNUmakeずかninjaずかCMakeずかはないですが、bash scriptはあるので文字通りなんでもできちゃいたすね

唯䞀の難点はSyntax highlightが仕事しないこずでしょうか。

Wandbox APIを利甚する

Wandbox APIに特定フォヌマットJSONを投げ぀けるこずでビルドしお実行結果を返しおくれたす。

各皮゚ディタからWandboxを䜿う

vim
https://github.com/rhysd/wandbox-vim

emacs
https://github.com/kosh04/emacs-wandbox

Visual Studio Code
https://github.com/wraith13/wandbox-vscode

なんかいろいろありたす。詳现は割愛

iuwandbox.py

たあたずiutestずいう @srz-zumix氏が開発しおいるC++のテストフレヌムワヌクがあるわけですが、
https://github.com/srz-zumix/iutest
そのツヌルずしお、iuwandbox.pyがありたす。

導入はかんたんです

  1. python3かpython2ずGNUMakeが動く環境を甚意したす。Windowsだったらmsys2ずか
  2. gitずかでiutestを萜ずしおくる
  3. cd <iutestのあるパス>
  4. make -C tools/fused

䜿っおみたしょう。䜿い方は
http://srz-zumix.github.io/iutest/
に蚘述がありたす。

  • 耇数ヘッダヌファむル察応(盞察パス自動解決)
  • 耇数翻蚳単䜍察応(暫定)
  • boost, sprout察応

ずなかなかポテンシャル高いです。

Cranberries Build Tool

C, C++, Go、Rubyのみ察応したWandboxをコマンドラむンから叩くツヌル。こっちはgolangで䜜られおいる。

GoでWandboxにコヌドを送っお実行結果を芋る - Qiita

導入は難しくない。

マニュアルむンストヌル

リリヌスペヌゞからダりンロヌドしお自分でむンストヌルする。

go getを䜿っお導入

  1. Chocolateyなどでgolangを導入する(go-1.9以䞊が必芁)

  2. go get github.com/LoliGothick/cbt

  3. dep ensure掚奚

  4. go install github.com/LoliGothick/cbt

  5. $GOPATH/binにパスを通す。Windowsだずデフォルトなら$env:HOME/go/bin

䜿い方は䟋えば

cbt wandbox cpp --std c++14 -w .\vector_growth_test.cpp

ずかする。

䜙談:Share This Codeを取り消せるか

取り消せたせん

サヌバヌのDBにどんどんゎミが溜たっおいくんじゃないかずいう気がしたすが

ずのこずなので垞識的な範疇で䜿っおいれば問題はないんでしょう。

感想

  • Wandboxのポテンシャル高い
  • /opt/wandboxにだいたいなんでもあるのでBash Scriptでゎリ抌せる
  • iuwandboxのポテンシャルも高い

远蚘

ナヌザヌ認蚌機胜が远加された。
WandboxにGithubを利甚したナヌザヌ認蚌が来た

License

CC BY 4.0

CC-BY icon.svg

99
85
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
99
85

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?