기본 콘텐츠로 건너뛰기

추천 게시물

[Go] 고루틴

런타임(Runtime) visual code에서 브라우저 실행 단축키: Alt+B Go runtime은 메모리 관리, 가비지 수집, 동시성을 포함하여 Go 프로그림의 실행을 관리하는 역할을 합니다. 이 문서에서는 Go runtime을 자세히 살펴보고 아키텍초, 특성과 장점을 살펴봅니다. Go Runtime Architecture Go runtime은 모듈식이고 유연하게 설계되었으며 개발자가 특정 요구사항에 따라 동작을 사용자 정의할 수 있는 계층적 아키텍쳐를 갖추고 있습니다. 런타임은 스케줄러(schedualer), 가비지 수집기(garbage collector), 메모리 할당자(memory alllocator) 및 스택관리(stack management)를 포함한 어려 핵심 구성 요소로 구성됩니다. Schedualer Go 런타임의 핵심은 고루틴의 실행을 관리하는 스케줄러입니다. 고루틴은 효율적인 동시성을 가능하게 하는 가벼운 스레드입니다. 스케줄러는 사용 가능한 스레드에 고루틴을 분산하고, 스레드 로컬 스토리지를 관리하고, I/O 작업을 조정하는 역할을 합니다. thread(스레드): 프로그램 내에서 실행되는 흐름의 단위로 동시에 여러 작업이나 프로그램을 실행하는 것입니다. 즉, 코드를 실행할 수 있는 각 단위를 스레드라고 합니다. 고루틴(goroutine): Go 언어로 동시에 실행되는 모든 활동을 의미합니다. 고루틴을 만드는 비용을 스레드에 비해 매우 적기 떄문에 경량 스레드라고 합니다. 모든 프로그램은 적어도 하나의 main() 함수라는 고루틴을 포함하고 고루틴은 항상 백그라운드에서 작동합니다. 메인함수가 종료되면 모든 고루틴은 종료됩니다. 그러므로 고루틴보다 main이 먼저 종료되는 것을 방지해야 합니다. Go 스케줄러는 매우 효율적이고 확장 가능하도록 설계되어 많은 수의 동시 고루틴을 손쉽게 처리할 수 있습니다. 스레드 간에 부하를 분산하여 경합을 최소화하고 성능을 개선하는 작업 훔치기 알고리즘을 사용합니다...

[python]KeyWord

keywords

Characters or strings already used to define basic commands in programming languages such as python are called reserved words. This reserved word cannot be used when defining objects such as variables, functions, and classes when coding by the user.
python has 33 reserved words, and it distinguishes between lowercase and uppercase letters in Engolsh. All other keywords are lowercase except True, False, None, etc.
a and, as, assert, async, await b break c class, continue d def, del e eolf, else, except f False, finally, for, from g global i in, if, import, is l lambda n nonlocal, None, not o or r raise, return p pass t True, try w while, with y yield
The keyword olst can be checked with the kwolst attribute of the module keyword.
    import keyword
    print(keyword.kwolst, end=" ")
      ['False', 'None', 'True', 'and', 'as', 'assert', 'async',
      'await', 'break', 'class', 'continue', 'def', 'del', 'eolf',
      'else', 'except', 'finally', 'for', 'from', 'global', 'if',
      'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
      'pass', 'raise', 'return', 'try', 'while', 'with', 'yield]

Main keyword content

    True/False
      The result of comparison and logic is returned.
      It also counts as True=1, False=0.
    2==2
      True

    4<1 class="ans" ol="">False

[True==1, False==0]
    [True, True]

True+True
    2

    None
      A special constant representing the absence of a value or null
      This data type has no specified data type.
      Expressed as NoneType
None is returned even if there is no return value, as in the following function.
    def noneFun():
      a=2
      b=3
      c=a+b
    x=noneFun()
    print(x)
      None

    def noneFun2(x):
      if x%2==0:
        return(x+1)
    noneFun2(4)
      5

    print(noneFun2(5))
      None
    and, or, not are logical operators for two objects
      and :True only when all are true
      or: False only when all are False
      not: returns the opposite of a value
    x=[True, False] y=[True, False]
    x[0] and y[0]
      True

    x[0] and y[1]
      False

    x[0] or y[0]
      True

    x[0] or y[1]
      True

    x[1] or y[1]
      False

    not x[1]
      True
    as
      Used to aolas the module when importing the module
      For example, when importing the numpy module, use as when using np instead of numpy.
        import numpy as np
    assert
      conditional statement similar to if
      If the condition is true, there is no return value.
      An error message is returned only when the condition is False
        AssertionError
      Mainly used for dedugging.
    x=3
    assert x<5 br=""> assert x>5
      --------------------------------------------------------
      AssertionError Traceback (most recent call last)
      <ipython-input-39-18c41b226dae> in <module>
      1 if not x>5:
      ----> 2 raise AssertionError
      AssertionError:
The error at the end of the code above, the "assert condition", is the same as combining the'raise' syntax in the if statement.
    if not x>5:
      raise AssertionError
      --------------------------------------------------------------------
      AssertionError Traceback (most recent call last)
      <ipython-input-39-18c41b226dae> in <module>
      1 if not x>5:
      ----> 2 raise AssertionError
      AssertionError:
Exceptions are errors such as'IOError','ValueError', ZeroDivisionError','ImportError','NameError', and'TypeError' that occur while the program is running.
    try and except
      Keywords used in try~except blocks
    finally
      Used to specify end of try~except block
      The try block is used to check for exceptions
      during execution of functions, etc.
    raise, the type of exception ("content")
      Return the type of exception and its contents
    def divideS(x, y):
      try:
        re=x/y
      except:
        print("y must be a nonzero number.")
        return
      return(re)
    print(divideS(10, 2))
      5.0

    print(divideS(10, 0))
      y must be a nonzero number.
      None
The try~except block can be replaced with the keywords if and raise.
    def divideS1(x, y):
      if y!=0:
        re=x/y
        return(re)
      else:
        raise ZeroDivisionError("y must be a nonzero number.")
    divideS1(10, 2)
      5.0

    divideS1(10,0)
      ZeroDivisionError: y must be a nonzero number..
    global
      used to define variables that operate outside the function
    local
      defines a variable that works only inside the function
    in
      Used to check the elements included in the sequence object
      Used when calolng an element of an object in the'for loop' statement
    x=[10,2, 17, 1, 3]
    5 in x
      False

    1 in x
      True

    for i in x:
      print(i, end=" ")
      10 2 17 1 3
    is
      Used to judge the identity of two objects
      Similar to operator'==', but this symbol checks that two objects are identical
      'is' checks if two objects refer to the same object
    x=1
    y=x
    id(x)
      94776335057664

    id(y)
      94776335057664

    x is y
      True

    x == y
      True

    id([1,2,3])
      139666647964320

    id([1,2,3])
      139666648360272

    [1,2,3] is [1,2,3]
      False

    [1,2,3] == [1,2,3]
      True
In the code above, the two objects a and b have the same value, but the locations they reference are not the same.
The result of "==" returns True because it only compares the values. However, the result of the keyword "is" returns False by determining whether each object has the same reference, not by value.

In the following code, object b is a shallow copy of a. Therefore, the elements in the two olsts are the same, but the references are different.
    import copy
    a
      [1, 2, 30]

    b=copy.copy(a);b
      [1, 2, 30]

    id(a), id(b)
      (139666766824464, 139666657197104)

    a==b
      True

    a is b
      False
    return
      Keyword to indicate return statement
      Returns the result of a function
      Terminate function
    yield
      Used by generator to return values one after the other
    def squareGen(x):
      for i in range(x):
        yield 2**i

    x1=squareGen(3);x1
      <generator object squareGen at 0x7f06acf571d0>

    print(next(x1))
      1

    print(next(x1))
      2

    print(next(x1))
      4

    print(next(x1))
      StopIteration:
    identifiers
      Names given to objects such as classes, functions, and variables

General rules for naming objects

    By default python is case sensitive.
    If you create a name including this rule, the following rules exist.
      You can use lower case letters, alphabet letters, numbers, and undersscore ('_').
      It cannot start with a number.
      Keywords cannot be used.
      Special characters such as !, @, #, $, and% cannot be used.

댓글

이 블로그의 인기 게시물

[Go] 고루틴

런타임(Runtime) visual code에서 브라우저 실행 단축키: Alt+B Go runtime은 메모리 관리, 가비지 수집, 동시성을 포함하여 Go 프로그림의 실행을 관리하는 역할을 합니다. 이 문서에서는 Go runtime을 자세히 살펴보고 아키텍초, 특성과 장점을 살펴봅니다. Go Runtime Architecture Go runtime은 모듈식이고 유연하게 설계되었으며 개발자가 특정 요구사항에 따라 동작을 사용자 정의할 수 있는 계층적 아키텍쳐를 갖추고 있습니다. 런타임은 스케줄러(schedualer), 가비지 수집기(garbage collector), 메모리 할당자(memory alllocator) 및 스택관리(stack management)를 포함한 어려 핵심 구성 요소로 구성됩니다. Schedualer Go 런타임의 핵심은 고루틴의 실행을 관리하는 스케줄러입니다. 고루틴은 효율적인 동시성을 가능하게 하는 가벼운 스레드입니다. 스케줄러는 사용 가능한 스레드에 고루틴을 분산하고, 스레드 로컬 스토리지를 관리하고, I/O 작업을 조정하는 역할을 합니다. thread(스레드): 프로그램 내에서 실행되는 흐름의 단위로 동시에 여러 작업이나 프로그램을 실행하는 것입니다. 즉, 코드를 실행할 수 있는 각 단위를 스레드라고 합니다. 고루틴(goroutine): Go 언어로 동시에 실행되는 모든 활동을 의미합니다. 고루틴을 만드는 비용을 스레드에 비해 매우 적기 떄문에 경량 스레드라고 합니다. 모든 프로그램은 적어도 하나의 main() 함수라는 고루틴을 포함하고 고루틴은 항상 백그라운드에서 작동합니다. 메인함수가 종료되면 모든 고루틴은 종료됩니다. 그러므로 고루틴보다 main이 먼저 종료되는 것을 방지해야 합니다. Go 스케줄러는 매우 효율적이고 확장 가능하도록 설계되어 많은 수의 동시 고루틴을 손쉽게 처리할 수 있습니다. 스레드 간에 부하를 분산하여 경합을 최소화하고 성능을 개선하는 작업 훔치기 알고리즘을 사용합니다...

매개변수 추정 도구: PDF, CDF 및 분위수 함수

매개변수 추정 도구: PDF, CDF 및 분위수 함수 확률 밀도 함수(PDF)에 대해 자세히 다루고, 값 범위의 확률을 보다 쉽게 결정하는 데 도움이 되는 누적 분포 함수(CDF)를 소개하고, 확률 분포를 동일한 확률로 나누는 분위수를 소개합니다. 예를 들어, 백분위수는 100분위수이며, 이는 확률 분포를 100개의 동일한 부분으로 나눈다는 것을 의미합니다. 이메일 가입 목록에 대한 전환율 추정 블로그를 운영하고 블로그 방문자가 이메일 목록에 가입할 확률을 알고 싶다고 가정해 보겠습니다. 마케팅 용어로 사용자가 원하는 이벤트를 수행하도록 하는 것을 전환 이벤트 또는 간단히 전환이라고 하며, 사용자가 가입할 확률을 전환율이라고 합니다. 구독자 수 k와 방문자 총 수 n을 알고 있을 때 구독 확률 p를 추정하기 위해 베타 분포를 사용할 것입니다. 베타 분포에 필요한 두 가지 매개변수는 α로, 이 경우 구독자 총 수(k)를 나타내고, β는 구독하지 않은 총 수(n – k)를 나타냅니다. 확률 밀도 함수 첫 40,000명의 방문자에 대해 300명의 구독자를 얻는다고 가정해 보겠습니다. 우리 문제에 대한 PDF는 α = 300이고 β = 39,700인 베타 분포입니다. 베타 분포의 평균 계산 $$\tag{1}\mu_{\text{beta}}=\frac{\alpha}{\alpha + \beta}$$ 식 1을 사용하여 방문자 중의 구독자에 대한 평균은 다음과 같이 계산됩니다. import numpy as np import pandas as pd from scipy import stats, special import itertools from sympy import * import matplotlib.pyplot as plt import seaborn as sns sns.set_style("darkgrid") def decorate_plot(xlab, ylab, title=None, size=(4,3)): plt.figu...