Path: blob/main/test/benchmark/benchmark_utf16.cpp
4133 views
// Copyright 2016 The Emscripten Authors. All rights reserved.1// Emscripten is available under two separate licenses, the MIT license and the2// University of Illinois/NCSA Open Source License. Both these licenses can be3// found in the LICENSE file.45#include <stdio.h>6#include <string.h>7#include <wchar.h>8#include <iostream>9#include <cassert>10#include <emscripten.h>1112EM_JS_DEPS(deps, "$UTF16ToString");1314double test(const unsigned short *str) {15double res = EM_ASM_DOUBLE({16var t0 = _emscripten_get_now();17var str = UTF16ToString($0);18var t1 = _emscripten_get_now();19out('t: ' + (t1 - t0) + ', len(result): ' + str.length + ', result: ' + str.slice(0, 100));20return (t1-t0);21}, str);22return res;23}2425unsigned short *utf16_corpus = 0;26long utf16_corpus_length = 0;2728unsigned short *randomString(int len) {29if (!utf16_corpus) {30// FILE *handle = fopen("ascii_corpus.txt", "rb");31FILE *handle = fopen("utf16_corpus.txt", "rb");32fseek(handle, 0, SEEK_END);33utf16_corpus_length = ftell(handle)/2;34assert(utf16_corpus_length > 0);35utf16_corpus = new unsigned short[utf16_corpus_length+1];36fseek(handle, 0, SEEK_SET);37fread(utf16_corpus, 2, utf16_corpus_length, handle);38fclose(handle);39utf16_corpus[utf16_corpus_length] = 0;40}41int startIdx = rand() % (utf16_corpus_length - len);42while((utf16_corpus[startIdx] & 0xFF00) == 0xDC00) {43++startIdx;44if (startIdx + len > utf16_corpus_length) len = utf16_corpus_length - startIdx;45}46assert(len > 0);47unsigned short *s = new unsigned short[len+1];48memcpy(s, utf16_corpus + startIdx, len*2);49s[len] = 0;50while(((unsigned short)s[len-1] & 0xFF00) == 0xD800) { s[--len] = 0; }51assert(len >= 0);52return s;53}5455int main() {56double t = 0;57double t2 = emscripten_get_now();58for(int i = 0; i < 10; ++i) {59// FF Nightly: Already on small strings of 64 bytes in length, TextDecoder trumps in performance.60unsigned short *str = randomString(100);61t += test(str);62delete [] str;63}64double t3 = emscripten_get_now();65printf("OK. Time: %f (%f).\n", t, t3-t2);66return 0;67}686970